Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Rx observable subscription in view holder: How to handle lifecycle?

I know that if I subscribe to an observable in an Activity or Fragment, I should bind it to their respectively lifecycle, using rxlifecycle-components or rxlifecycle-navi.

However, I'm now subscribing to an observable from inside a ViewHolder (extends RecyclerView.ViewHolder), and I'm worried what would happen if the view is destroyed and the subscription remains active.

To which lifecycle should I bind this observable and how ?

like image 825
FlyingPumba Avatar asked Jul 26 '16 01:07

FlyingPumba


2 Answers

RecyclerView.Adapter has a method onViewRecycled(ViewHolder) where you can close the subscriptions of the ViewHolder argument.

like image 189
Karakuri Avatar answered Sep 20 '22 03:09

Karakuri


I, hopefully, found the answer while writing the question.

Most Adapters receive a Context parameter in their constructor, among other things. For example:

public MyAdapter(Context context, ... ) { ... }

We can change it to receive a RxActivity, which in turns works as context also:

public MyAdapter(RxActivity parent, ... ) {
  this.parent = parent;
  ...
}

And now in the ViewHolder:

myObservable
   .compose(parent.bindToLifecycle())
   .subscribe();

This ensures that any subscription will end if the parent (activity or fragment) is destroyed.

like image 22
FlyingPumba Avatar answered Sep 21 '22 03:09

FlyingPumba