core
core copied to clipboard
should ngx-translate service subscribe calls be unsubscribed to avoid mem leaks?
Hi! The docs said that any questions should be addressed here, so I have a question please:
In the usage guide it says the translations done with the service should be subscriptions i.e.
With the service, it looks like this:
translate.get('HELLO', {value: 'world'}).subscribe((res: string) => { console.log(res); //=> 'hello world' })```
My question is, should I actually also UNsubscribe in my onDestroy event, for each of these resources I subscribe to, whenever I translate from service directly ? The Usage guide has no mention of this aspect or I could not find it. I ask because potentially these could be a lot of subscriptions to unsub from, and it feels redundant because you might have some form of cleaning already built-in, so I just want to be sure what I should do. Thanks!
@andreimcristof I also thought about this and docs doesnt say nothing about it. I think we should
use the takeWhile
approach.....
Maybe the main reason for not mention anything in docs is because this is an Angular pattern which is not directly related to this library, as you mention you could unsubscribe for avoid mem leaks, however you should also not be using the get method too much, please try to use always the directive or pipe approach
Its not required to call unsubscribe as the translate.get() method will automatically completes the observable.
Below is the source code for your reference.
only for methods like stream
you should unsubscribe!
@manandkumaar This should definitely be written in the docs!
This should be in the docs. The lack of need for an unsubscribe is a pattern that is not rxjs specific, but specific for the likes of angular and apparently ngx-translate. 'If you know js' (read as rxjs) you should always assume you'd need to unsubscribe.
"subscribe" here has the role of "then", it's a promise, nothing else
only for methods like
stream
you should unsubscribe!
How to unsubscribe the translate.stream??
What about onLangChange
? Do we need to unsubscribe from that?
@suprishi Yes, Please see here: https://github.com/ngx-translate/core/issues/319#issuecomment-259935416
@jagadeesh93 It is just a normal unsubscribe way. e.g. https://github.com/ngx-translate/core/issues/319#issuecomment-259935416
cribe the tr
subscript = new Subscription(); const sub= this.translate...... ....).subscribe(); this.subscript.add(sub);
ngOnDestroy() { this.subscript.unsubscribe(); }