I am new to Angular (just learning) and I am trying to understand the following code. In this code (I simplified it from another app I have seen on Github) subscribe
method calls add
method with the parameter resolve
(from Promise) - so I have a few questions:
- Doesn't parameter passed to add mehtod have to be of type `Subscription' ?
- What does framework do with passed
resolve
parameter. I Thought the parameter must be of type Subscription and framework calls<Subscription>.unsubscribe()
on it.
const numbers: Observable<number> = interval(5000);
const takeFourNumbers = numbers.pipe(take(4));
const promise$ = new Promise<void>(resolve => {
// attempt to refresh token on app start up to auto authenticate
takeFourNumbers.subscribe()
.add(resolve);
}).then((result) => {
console.log("My result is ", result);
});
CodePudding user response:
That's a bit of an odd piece of code.
Every Subscription
has an .add(
function, which is used to trigger something else on teardown, this is when that subscription ends (either because the stream errors, completes, or you call .unsubscribe())
The parameter that .add(
takes can be a function (in which case it just gets called on teardown), or another subscription, in which case it will call .unsubscribe()
to it.
It's not really used too much unless you're building something low-level (such a library)
In this case, takeFourNumbers
is a stream that will emit 4 numbers in succession, 1 second between each emission and then complete. promise$
is a Promise that when takeForNumbers
ends after 4 seconds it will resolve with void
, because the teardown will call the function passed to .add(
, which is resolve, and it doesn't give any parameter as far as I know.
Then on that promise it calls .then(
to log the result when that happens, but I expect the result to be undefined
.