TAGS :Viewed: 9 - Published at: a few seconds ago

[ When should I unsubscribe from observables in activities and fragments to avoid negative consequences? ]

I have subscribers that interact with UI components of an activity/fragment. I'm not sure where and when should I unsubscribe them. I see two ways: the former is to unsubscribe them in the onPause() method, the latter is to unsubscribe them in the onStop() method. Which one is correct and why? Thanks

Answer 1


You should use onPause as you don't need the listener running while the activity or fragment is not. onPause gets called everytime the item is no longer activity running. onStop is called on the way to destruction.

Answer 2


"But what if my observable downloads some content after the activity starts" For long time operations or operations that must be independent from Activity Lifecycle you shuold use Service component

Answer 3


Please take a look at this https://github.com/trello/RxLifecycle. It will prevent your app from throwing NPE on views and context memory leaks. Read about MVP pattern. Below I made exemplary implementation

Presenter class

public class SamplePresenter {

    @NonNull
    private final Observable<SomeData> someDataObservable;

    public SamplePresenter(@NonNull ApiService apiService) {

        someDataObservable = apiService.apiRequest()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());
    }

    @NonNull
    public Observable<SomeData> getSomeDataObservable() {
        return someDataObservable;
    }
}

MainActivity class

@Inject
SamplePresenter samplePresenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    samplePresenter.getSomeDataObservable()
            .compose(this.<SomeData>bindToLifecycle())
            .subscribe(new Action1<SomeData>() {
                @Override
                public void call(SomeData someData) {

                }
            });