Will an interval which got piped run in RxJS?
Here is what I mean. Let us suppose we have the following code:
const arr = ["foo", "bar"];
const i = interval(500);
const toRun = i.pipe(
map(index => arr[index]),
take(arr.length)
);
toRun.subscribe(val => val);
Do I understand correctly, that the code works as follows:
1 The i
is created, but won`t be run until we subscribe to it.
2 With the help of the pipe
method we create a new Observable
, which is built upon the i
and works as follows:
- each 500ms emit an iteration number (0, 1, 2, ...)
- use the iteration number to extract a value from the
arr
- emit the extracted value to whoever was subscribed to the
pipe
method result - stop the emitting of the iteration numbers when the iteration number is greater than the
arr.length
So, the toRun.subscribe(val => val);
will emit foo
, then after 500ms bar
and will stop running. While the i
will never emit anything, since no one has subscribed to it.
I want to understand how this works, so, please, correct my explanation to answer my question if I am wrong.
I stumbled other the question, while working through the Angular documentation. More specifically through the async pipe. I met there the following example:
import { Component } from '@angular/core';
import { Observable, interval } from 'rxjs';
import { map, take } from 'rxjs/operators';
@Component({
selector: 'app-hero-message',
template: `
<h2>Async Hero Message and AsyncPipe</h2>
<p>Message: {{ message$ | async }}</p>
<button (click)="resend()">Resend</button>`,
})
export class HeroAsyncMessageComponent {
message$: Observable<string>;
private messages = [
'You are my hero!',
'You are the best hero!',
'Will you be my hero?'
];
constructor() { this.resend(); }
resend() {
this.message$ = interval(500).pipe(
map(i => this.messages[i]),
take(this.messages.length)
);
}
}
And I got curious whether or not there may be performance issues due to the unnecessary running of the interval(500)
(since the pipe
will create a new observable and the interval(500)
won`t be used explicitly, but only by the pipe
during the new observable creation).