Return a completable in RxSwift without using a create block

Yasir picture Yasir · Jul 15, 2017 · Viewed 9.1k times · Source

I have a Completable being returned from a simple function. This is not an async call, so I just need to return a succcessful completion or error depending on a conditional (using Rx here so I can tie into other Rx usages):

func exampleFunc() -> Completable {
    if successful {
        return Completable.just() // What to do here???
    } else {
        return Completable.error(SomeErrorType.someError)
    }
}

The error case works pretty easily, but am having a block on how to just return a successful completable (without needing to .create() it).

I was thinking I just need to use Completable's .just() or .never(), but just is requiring a parameter, and never doesn't seem to trigger the completion event.

Answer

Yasir picture Yasir · Jul 15, 2017

.empty() is the operator I was looking for!

Turns out, I had mixed up the implementations of .never() and .empty() in my head!

  • .never() emits no items and does NOT terminate
  • .empty() emits no items but does terminates normally

So, the example code above works like this:

func exampleFunc() -> Completable {
    if successful {
        return Completable.empty()
    } else {
        return Completable.error(SomeErrorType.someError)
    }
}

Here is the documentation on empty/throw/never operators.