简体   繁体   中英

Why doesn't `finally` work in this case in RxJS?

This does not print "drag end":

mouseDrags.forEach(drag => {
    console.log('drag start');
    drag.finally(_ => console.log('drag end'));
    drag.forEach(doSomething);
});

But this prints "drag end":

mouseDrags.forEach(drag => {
    console.log('drag start');
    drag.finally(_ => console.log('drag end')).forEach(_=>_);
    drag.forEach(doSomething);
});

Why does the forEach make a difference?

It is because .finally() returns another Observable which you need to subscribe to. Observable s are by default lazy, so they won't start emitting until they are subscribed to.

So you can do

mouseDrags.forEach(drag => {
    console.log('drag start');
    drag.finally(_ => console.log('drag end')).forEach(doSomething);
});

or even better

mouseDrags.flatMap(drag => {
    console.log('drag start');
    return drag.finally(_ => console.log('drag end'))  
}).forEach(doSomething);

What is the type of drag ? If it is an Observable, you need to subscribe to it. finally doesn't subscribe, but forEach does. You could test it by calling drag.finally(_ => console.log('x')).subscribe() . That should print it too.

The forEach is in fact an alias for subscribe , so using either is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM