Issue
To learn rxjs im playing around with it. My code:
// RxJS v6+
import { withLatestFrom, map } from 'rxjs/operators';
import { interval } from 'rxjs';
const source = interval(1000);
const example = source.pipe(
map(value => value +1),
map(value => {
if(value === 40) {
finish();
}
else if (value % 5 === 0){
return 'can devide by 5 we did some magic';
}else{
return value;
} })
);
const subscribe = example.subscribe(
val => console.log(val),
error => console.log("Error handled: " , error),
() => console.log('resolved'));
My idea was to run it 40 time and than finish the observable (it could be another requirement e.g. see if the value is 10 at 10:00 (main goal is to do an evaluation with value and force a finish)).
Im looking for an alternative to the placeholder finish() because finish does not exist. How can I get to the resolve function () => console.log('resolved')
of the subscribe method?
I found How can I complete Observable in RxJS but the answer is from 2015 and im assuming by now there is an answer for the current rxjs version.
Solution
both answers mention takeuntil and take are correct but another way is to use the subscription object to unsubscribe it just another option
const subx= example.subscribe(val => {
console.log(val);
if (val == 40) {
subx.unsubscribe()
}
});
Updated 😎
in case you have a many subscribers and you want to put the condtion that complate a source observable take operator can do the job here
const source = interval(1000).pipe(take(5)); // 👈
source.pipe(map(res => res * 10)).subscribe(val => {
console.log("🤯", val);
});
source.subscribe(val => {
console.log(val);
});
Answered By - Muhammed Albarmavi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.