RxJs difference between complete and unsubscribe in Observable?
Asked Answered
S

2

32

After complete event will unsubscribe Observable or not or any other difference?

Sevastopol answered 6/9, 2018 at 7:2 Comment(2)
Possible duplicate of: #48771850Morehouse
Possible duplicate of RxJS Subscriber unsubscribe vs. completeCymoid
J
51

You complete an Observable, and unsubscribe a Subscription. These are two different methods on two different objects. You subscribe to an observable which returns a Subscription object.

If you want to stop listening to emits from the Observable you call subscription.unsubscribe().

If you want an Observable to be done with his task, you call observable.complete(). (this only exists on Subject and those who extend Subject). The complete method in itself will also unsubscribe any possible subscriptions.

When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription. Observers do not need to issue an Unsubscribe notification to end subscriptions that are ended by the Observable in this way.

Jiggered answered 6/9, 2018 at 7:18 Comment(4)
where did you read about "The complete method in itself will also unsubscribe any possible subscriptions."? Does that mean that having 2 subscriptions and if we complete the Observable without unsubscribing the 2 Subscriptions will handle the unsubscribe() method for us? In other words, is the unsubscribe() optional if we complete() the Observable?Harrus
@DiegoOsornio that is true, the unsubscribe is optional, you can read about it in the reactivex contract documentation. I'll update my answer with a quote from this docJiggered
best explainationExpand
"When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription. Observers do not need to issue an Unsubscribe notification to end subscriptions that are ended by the Observable in this way." Subscribing and UnsubscribingGenerative
E
12

If you complete an Observable, it will call complete() method then the teardown logic and unsubscribe(). Calling unsubscribe() itself does not call complete method. Angular async pipe is an example of calling unsubscribe. Therefore, if you have complete method and using async pipe, it will not be called.

Ephebe answered 6/9, 2018 at 7:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.