Reputation: 3556
I'm using the pattern from RxJs like so.
serviceThatMayNotComplete
.obtainObservableOfSomeKind(url)
.subscribe(res => console.log(res));
When the component is done, I understand that I need to unsubscribe to avoid memory leaks. Since I know that the service will only produce a single value, ever, I tried to find a version of subscribe
that only picks one element (a bit like the promisses did).
I've located take and first but it seems that they are operators on the set to be emitted and not how the consumption is performed.
Googling gave little I recognized as helpful but I might be using poor key words.
Is there a version of subscribe
that dies after a single response being delivered?
Upvotes: 1
Views: 343
Reputation: 6283
Mix together pipe operator and take(1), this should get you the first value and then unsub automatically.
http.get(url)
.pipe(take(1))
.subscribe(res => console.log(res));
In such scenarios we can use RxJS take(1) operator which is great because it automatically unsubscribes after the first execution.
Mentioned in this article
Also, be aware, when using angular's default HttpClient for that get
request, the cleanup is already taken care of by the framework for you.
Upvotes: 2
Reputation: 3576
If you only want to observe the first value, then you can use first()
Assuming that http.get()
returns a observable, you can do:
http.get(url).first().subscribe(
//your code
);
Note:
first()
will unsubscribe automatically when their condition is met.
Upvotes: 1