0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It seems like timer could be used as described in my example. I'm just not sure what is wrong with it.
I have update the answer with a little explanation about timer operator. Check as correct if you think

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.