11

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.

Yasir
  • 2,312
  • 4
  • 23
  • 35

2 Answers2

34

.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 terminate 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.

Yasir
  • 2,312
  • 4
  • 23
  • 35
0

I would be more inclined to do the following:

func example() throws {
    // do something
    if !successful {
        throw SomeErrorType.someError
    }
} 

Then in order to tie it into other Rx code, I would just use map as in:

myObservable.map { try example() }

But then, mapping over a Completable doesn't work because map's closure only gets called on next events. :-(

I tend to avoid Completable for this very reason, it doesn't seem to play well with other observables. I prefer to use Observable<Void> and send an empty event before the completed...

Something like this:

let chain = Observable<Void>.just()
let foo = chain.map { try example() }
foo.subscribe { event in print(event) }
Daniel T.
  • 32,821
  • 6
  • 50
  • 72
  • Good points. I am trying to occasionally use traits so I understand their use cases and limitations better - noticed concat and merge operators had been added to Completable in [v3.5.0](https://github.com/ReactiveX/RxSwift/blob/master/CHANGELOG.md) so hoping they get easier to integrate with other flows as more operators are added! – Yasir Jul 16 '17 at 10:07