AutoDispose: How to handle error from observable after life cycle expires

824 views Asked by At

I use RxJava to run http operations in the background. I use lifecycle transformer to avoid getting events when activity has finished (initially Trellos RxLifeCycle, now I'm experimenting with AutoDispose). My problem is if the activity finished, and then the background job throws an exception then I get an exception which crashes the app from RxJava.

The question is: Is it possible to use a life cycle provider (AutoDispose), and yet still handle the exception thrown by a producer, thus avoiding it being propagated by RxJava to the main thread and killing the app?

The below code waits for activity to stop, then throws exception. The Android app crashes unless I remove the AutoDispose line.

 Observable.create(e -> {
            // Wait for life cycle to see my activity is stopped, then throw simulation IOException    
            while (!stopped) {
                Log.d(TAG, "Sleeping");
                try { Thread.sleep(1000); } catch (InterruptedException ignore) {}
            }
            throw new IOException("No AutoDispose 1");
        }).subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .to(AutoDispose.with(AndroidLifecycleScopeProvider.from(activity, Lifecycle.Event.ON_STOP)).forObservable())
                .subscribe((it) -> {}, (throwable -> Log.w(TAG, "Caught error  " + throwable)));

This question relates to AutoDispose because I plan on moving on due to problems mentioned by Dan Lew. Though I am curious if the problem could also be solved with RxLifeCycle.

Here's a full activity for easier execution @ gist

1

There are 1 answers

0
Zac Sweers On

A bit late to the party, but was eventually answered in https://github.com/uber/AutoDispose/issues/164#issuecomment-393727626

A well-behaved source will check isDisposed() before emitting events. In the case of sleeping, it's really a best-effort thing.