Z
Z
zlodiak2018-03-04 01:05:27
JavaScript
zlodiak, 2018-03-04 01:05:27

How to output the result of a do statement after the main action?

Code like this:

Observable.timer(0, 3000).do((v) => console.log('tick', v)).subscribe((r) => {
      console.log(r);
    });


Outputs this:
tick 0
0
tick 1
1
tick 2
2
tick 3
3


But it is not clear to me why in the record of the do statement comes AFTER timer, but BEFORE timer is displayed. Is it possible to make the result of the do statement appear after the number that the timer generates?

And in general, no one finds the action of this operator strange? ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmitrygavrish, 2018-03-04
@zlodiak

The do statement does not affect the sequence in any way, you just “wedge” into it, get its current data and can launch any side effects based on this data (the result of the function execution in do does not affect the data that will be in the next statement, or end subscription). You are subscribed to the timer itself after the do statement, so the actions in do will be performed first, then in subscribe.
In the same way, any action will be performed in any other statement before you get to subscribe, but other statements change the original sequence in one way or another.
To achieve the behavior you want, you can write the sequence to a variable and subscribe to it 2 times in the desired order:

const obs = Observable.timer(0, 3000);
obs.subscribe(i => console.log(i));
obs.subscribe(i => console.log('tick', i));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question