Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a completable in RxSwift without using a create block

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.

like image 666
Yasir Avatar asked Jul 14 '17 23:07

Yasir


People also ask

What is Completable Rxswift?

A Completable represent a Observable that can only complete or emit an error. It's equivalent to Observable<Void> that can't emit elements. Emits zero elements. Emits a completion event, or an error. Doesn't share side effects.

What is traits in RxSwift?

Traits are observables with a narrow set of behaviors. Traits are simply a wrapper struct with a single read-only Observable sequence property.


1 Answers

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

like image 182
Yasir Avatar answered Sep 19 '22 06:09

Yasir