47

I'm using an RxJava ReplaySubject in my Fragment.

I'm attempting to use the ReplaySubject in a way, where I would like the Subject to execute a process until completion (possibly beyond the life of the fragment).

On completion of the process, I would like to release the resources which -as i understand- is done by unsubscribing the subscription at the time of registering the observer (which in my case, is the subject itself).

In this github issue thread @benjchristensen says:

If it is an Observable then it should emit an onCompleted and be done.

If it is an Observer then it should unsubscribe from the Subscription it received when it called Observable.subscribe and it will give the Observable a chance to shutdown and clean up.

If it's a Subject -which is both an Observer and an Observable- what is the behavior? If i call onComplete on the subject, does that basically mean the subscription is stopped, and I am therefore relieved of needing to manually unsubscribe the subscription i get by registering the observer?

Community
  • 1
  • 1
KG -
  • 7,130
  • 12
  • 56
  • 72

1 Answers1

64

Subjects are a relatively thin layer on top of an Observable that allow you to feed onNext(), onCompleted() and onError() calls from a source external to the Observable. Their unsubscribe behavior is the same as an Observable. If onCompleted() or onError() are called on the Subject, the subscribers will be unsubscribed. No need to call unsubscribe() on the subscription returned from Observable.subscribe().

For a ReplaySubject, note that resources will not be cleaned up until it is garbage collected. Even after onCompleted() has been called on a ReplaySubject, a subscriber can still subscribe and it will receive all of the original onNext(), onCompleted() or onError() calls that were made previous to subscribing.

Marcin Koziński
  • 10,835
  • 3
  • 47
  • 61
kjones
  • 5,783
  • 2
  • 27
  • 27
  • Is this also true for .cache and .replay transformed observables? – medihack Jul 15 '16 at 14:23
  • 2
    Is this mentioned in the documentation somewhere? I literally spent 1 hour on this today before I found this thread. – Deniss B. Feb 08 '17 at 16:38
  • @DenissB. I don't remember seeing anything in the documentation. Personally, I don't rely on this behavior. I always save off my subscriptions and then unsubscribe since calling unsubscribe on an already unsubscribed subscription has no effect. – kjones Feb 08 '17 at 20:39
  • But what if I need to subscribe again? Subject is completed and I can't connect to it again (it is just return onComplete). Could you give me advise? – Georgiy Chebotarev Nov 28 '19 at 12:49