Home > Software design >  RxJS timer doesn't wait for specified time?
RxJS timer doesn't wait for specified time?

Time:02-28

I'm trying to wrap my head around RxJS. While doing some testing, I ran into something that I can't figure out.

Here is the code :

let product = { id: 1, description: 'table' };

const asyncProduct = timer(2000).pipe(() => of(product));

asyncProduct.subscribe(data=>console.log(data))

I expected product to be logged into my console after 2 seconds, however, it logs right away for some reason. What do I misunderstand? Thanks.

CodePudding user response:

to emit after n seconds, you need to use delay operators not timer.

So you need to change your code in this way:

const asyncProduct = of(product).delay(2000)

asyncProduct.subscribe(data => console.log(data))

UPDATE: You can use timer operator with pipe and then with another operator in it like the following:

timer(2000).pipe(
switchMap(() => of(product))
).subscribe(data => console.log(data))

In this way the value will emot after 2 seconds, achieving your goal. Is another way instead of the first example that I have provided before.

  • Related