Simpler way to Observable.switchMap(Completable) w/error handling?

177 views
Skip to first unread message

Gino Miceli

unread,
May 18, 2019, 11:28:08 AM5/18/19
to RxJava

Thanks for a great implementation of ReactiveX!


We have several case where we're trying to implement the following pattern:


1. User clicks "Save Foo". If a previous save was still pending (e.g., never finished) it's aborted and previous subscription released.

2. Foo is asynchronously sent to database to be saved

3. A "Foo saved" message is shown once the operation completes and the screen is closed.


We'd ideally have one subscription per UI instance, rather than one per operation, so that we don't need to manually keep track of many subscriptions to avoid leaking memory in our Android app.

To do this, we have an `Observable<Foo> saveFooClicks` in our view, a method `Completable saveFoo(Foo)` in our data store, and the following code to set up the stream and subscription:


    disposeOnClear( saveFooClicks .switchMap( foo -> saveFoo(foo) .doOnComplete(() -> onSaveFoo(foo)) .onErrorComplete() .toObservable()) .subscribe());


Note that we use `onErrorComplete()` to avoid breaking the upstream Observable in case `saveFoo()`’s Completable terminates with an error. We could also wrap the potential errors in another object and propagate them to the outer stream, but since this is all being done in the same context, that seems unnecessary.


Is there a more idiomatic, intuitive way of doing this? Or are we simply holding it wrong?


Thanks in advance!


-Gino

groundplatform.org



Gino Miceli

unread,
May 18, 2019, 11:34:03 AM5/18/19
to RxJava
Note: In my example I meant to include a predicate in onErrorComplete() or a call to doOnError() to handle errors.
Reply all
Reply to author
Forward
0 new messages