There are several situations in my codebase where a stream I'm subscribing to will only ever emit one result and as such it makes sense to use rx.Single
rather than rx.Observable
. The documentation for Single says the following:
A Single will call only one of these methods, and will only call it once. Upon calling either method, the Single terminates and the subscription to it ends.
With a traditional Observable
I capture a reference to the Subscription so that I can unsubscribe at an appropriate time and not cause memory leaks:
Subscription s = getObservable().subscribe(...);
subscriptions.add(s);
subscriptions.clear();
My question is whether this is necessary with a Single or whether due to the fact that the subscription ends immediately it could be left simply as:
getSingle.subscribe(...);
Without any negative repercussions of references being held onto into the subscriber.
You need to cancel your job properly via Observable::create and Observable::flatMap. And set your cancalable in Observable::create.
In these cases, the observable will call . complete() after it has emitted all of it's values. There's no need to unsubscribe. It completes on it's own, which means it unsubscribes all subscribers automatically.
RxJava 2 introduced the concept of Disposables . Disposables are streams/links/connections between Observer and Observable . They're meant to give power to the Observers to control Observables . In most cases, the Observer is a UI element, ie; Fragment , Activity , or a corresponding viewmodel of those elements.
A Single is something like an Observable, but instead of emitting a series of values — anywhere from none at all to an infinite number — it always either emits one value or an error notification.
Single
doesn't tell you anything about how long it will be running.
Since you're targeting Android, the answer is yes, you should keep the subscription and unsubscribe.
Imagine you're switching Fragments/Activities and a long running SingleSubscribers's
onSuccess
is called. So the best time and space is probably in onPause()
, but it depends on your context.
You might run into NullPinterExceptions
, Adapters being filled multiple times or similar problems if you don't unsubscribe.
Any reason why you need to cleanup the subscription on Observable?. Observable by design once that the observer has all items is automatically unsubscribed.
And then, since the instance is not reference anymore the GC at some point will clean up for you.
You can see in these example how the subscription is unsubscribe after onComplete is reach.
https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/creating/ObservableSubscription.java
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