As this article says, CompositeSubscription is hard to use in Android activities / fragments because there is no way to re-initialize its instance.
I wonder why its clear() method does not clear its state. Is there any reason about it? Or, is it just a bug in COmpositeSubscription?
RxJava containers are designed with a terminal state in mind. When a container gets into its terminal state via unsubscribe() atomically, all previous contained elements are unsubscribed and all subsequent add/set of a Subscription is immediately unsubscribed and never added to the container. Since unsubscription is highly asynchronous, checking isUnusbscribed() is not sufficient to avoid starting tasks or creating resources in case of a concurrent unsubscribe call.
The clear method removes all contained subscription and unsubscribes them, but you can add new subscriptions to the composite after that.
In android terms, imagine you have a background task which wants to add a Subscription to the app composite just after your app is signalled to pause. Without a guaranteed terminal state, your async task would succeed and now you have a resource leak. With the guaranteed terminal state, the resource is immediately unsubscribed and no leak happens.
As the article says, you need to replace the composite with a fresh one and restart any async observations as needed.
Thanks to describe details. I have understood that it is designated behavior and making a new instance of CompositeSubscription is the only way to control it.
JavaDoc says clear() makes the composite "unoperative state", but actually it does NOT.
Most helpful comment
RxJava containers are designed with a terminal state in mind. When a container gets into its terminal state via
unsubscribe()atomically, all previous contained elements are unsubscribed and all subsequent add/set of a Subscription is immediately unsubscribed and never added to the container. Since unsubscription is highly asynchronous, checkingisUnusbscribed()is not sufficient to avoid starting tasks or creating resources in case of a concurrent unsubscribe call.The
clearmethod removes all contained subscription and unsubscribes them, but you can add new subscriptions to the composite after that.In android terms, imagine you have a background task which wants to add a Subscription to the app composite just after your app is signalled to pause. Without a guaranteed terminal state, your async task would succeed and now you have a resource leak. With the guaranteed terminal state, the resource is immediately unsubscribed and no leak happens.
As the article says, you need to replace the composite with a fresh one and restart any async observations as needed.