Ricardo Carrapiço
Ricardo Carrapiço

Reputation: 270

RxJava chain calls that follow an Observable<Void>

I've been wrapping a synchronous library so every method that does IO returns an Observable. However some of these methods return Observable<Void> as I'm only caring about its completion.

How do I chain calls after an Observable that doesn't emit anything?

accountManager.doAuth()
            .flatMap(x -> paginator.next())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(... subscriber stuff ...)

I have to call doAuth for every request and it returns Observable<Void>. Since it doesn't emit items, onNext is never called, only onCompleted.

Regarding doAuth I only care if it completes or gives an error. If it completes I would like that paginator.next() was called so I could implement my own logic in onCompleted/onError/onNext.

Until now I've been using flatMap to chain calls and it works fine when I actually care about the things that the previous Observables returned.

Upvotes: 2

Views: 2946

Answers (1)

eleven
eleven

Reputation: 6855

Since release of 1.1.1 RxJava has Completable which perfectly fits your requirement. Instead of returning Observable<Void> you could return Completable:

public Completable doAuth(){
    return Completable.create(subscriber -> {
        //do auth
        if(authOk) subscriber.onCompleted();
        else subscriber.onError(throwable);
    });
}

Great articles about Completable: part one, part two

Upvotes: 5

Related Questions