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 ?
RecyclerView.Adapter
has a method onViewRecycled(ViewHolder)
where you can close the subscriptions of the ViewHolder
argument.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With