What the better way to unsubscribe observable in your opinion? (Subscription.add or takeUntil).I think what Subscription.add better because for takeUntil need excess observable
Asked
Active
Viewed 6,979 times
3
-
1The best way is not to subscribe in the first place. Use the `async` pipe – C.OG Dec 28 '19 at 21:13
-
can you add your example? It will be easier to answer with more data – Oded BD Dec 28 '19 at 21:34
-
1This should be reopened. The question mentions two different approaches and what is the difference between them. It's not very much opinion-based imho. – martin Dec 28 '19 at 22:49
-
@C_Ogoo If you are using Angular, you should be using observables rather than converting it into a promise – wentjun Dec 29 '19 at 02:43
-
Quite a few similar questions which discusses the different approaches when it comes to handling subscriptions and unsubscriptions (https://stackoverflow.com/questions/58428791/angular-rxjs-observable-takeuntil-vs-unsubscribe-with-a-subscription/58429338#58429338, https://stackoverflow.com/questions/56672547/how-to-implement-ngondestroy-correctly-in-angular-5/56673005#56673005, https://stackoverflow.com/questions/58460256/angular-observables-do-i-need-unsubscribe-if-no-subscription/58460534#58460534) – wentjun Dec 29 '19 at 02:45
-
take a look at this https://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/ – Reza Dec 29 '19 at 02:56
-
it's better to use subscription, because takeUntil requires you to put it in the right place(usually last). Subscription will always unsubscribe without any issue. I always prefer it – cuddlemeister Dec 29 '19 at 08:32
2 Answers
0
It depends on your situation, you could just use async
pipe in the template for automatic unsubscription
and takeUntil
operator if you are using an observable in the component.
0
As Lex Caraig mentioned, you could just use async
pipe in the template. But when it comes to component, you need understand the pros & cons of both unsubscribe
and ```takeUntil operator.
Personally I prefer to use subscription.add
& subscription.unsubscribe
than takeUntil
, because of its side-effects. Please go through the below article to understand more about the side-effects.
https://cartant.medium.com/rxjs-avoiding-takeuntil-leaks-fb5182d047ef