29

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

CharithJ
  • 46,289
  • 20
  • 116
  • 131
Sourabh
  • 644
  • 1
  • 7
  • 14
  • Possible duplicate of: https://stackoverflow.com/questions/48771350/rxjs-subscriber-unsubscribe-vs-complete – Ritesh Waghela Sep 06 '18 at 07:16
  • Possible duplicate of [RxJS Subscriber unsubscribe vs. complete](https://stackoverflow.com/questions/48771350/rxjs-subscriber-unsubscribe-vs-complete) – Buggy Sep 06 '18 at 07:50

2 Answers2

46

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.

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • 2
    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 `Subscription`s will handle the `unsubscribe()` method for us? In other words, is the `unsubscribe()` optional if we `complete()` the Observable? – Diego Osornio Nov 19 '19 at 21:46
  • 5
    @DiegoOsornio that is true, the `unsubscribe` is optional, you can read about it in the reactivex contract [documentation](http://reactivex.io/documentation/contract.html). I'll update my answer with a quote from this doc – Poul Kruijt Nov 20 '19 at 08:15
  • 1
    best explaination – minigeek Jan 11 '22 at 11:48
  • 1
    _"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 Unsubscribing](https://reactivex.io/documentation/contract.html) – Jnr Feb 12 '23 at 05:02
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.

dK-
  • 582
  • 3
  • 12