[英]rxjs finally executed before promise resolves
Below is a simplified version of my code. 下面是我的代码的简化版本。 The problem is that the finally block is executed early than I would like.
问题是finally块的执行时间比我想要的要早。 I would like it to execute only when all the other Observables are done.
我希望它只在所有其他Observable完成时才执行。
let data1 = 'test1'
let data2 = 'test2'
const input = Rx.Observable.from([data1, data2])
.finally(() => {
console.log('end')
})
let output = input.concatMap((text) => {
let promise = Promise.resolve(text)
return Rx.Observable.fromPromise(promise)
})
output.subscribe((x) => {console.log(x)})
Output: 输出:
end
test1
test2
Expected output: 预期产量:
test1
test2
end
The problem you have is that Observable.from
emits everything immediately and completes. 你遇到的问题是
Observable.from
会立即发出一切并完成。 Then both emissions are buffered inside concatMap
but the source has already completed so the finally
block is called. 然后两个发射都在
concatMap
中缓冲,但源已经完成,因此调用了finally
块。
The easiest thing you can do is just put the finally
block after concatMap
because that's when it's really done: 你能做的最简单的事情就是在
concatMap
之后放置finally
块,因为那是在它真正完成的时候:
const data1 = 'test1';
const data2 = 'test2';
const input = Observable.from([data1, data2]);
const output = input
.concatMap(text => Promise.resolve(text))
.finally(() => console.log('end'));
output.subscribe(console.log);
See live demo (open console): https://stackblitz.com/edit/rxjs5-hnesmn?file=index.ts 查看现场演示(开放式控制台): https : //stackblitz.com/edit/rxjs5-hnesmn?file = index.ts
Btw, if you really need .finally
right after Observable.from
you can't get the output you want because .finally
is called when Observable.from
is disposed (completed or errored), which is independent of the chain that follows. 顺便说一句,如果你真的需要
.finally
右后Observable.from
你不能得到你想要的,因为输出.finally
,当被称为Observable.from
配置(已完成或出错),它是独立的后面的链条。 In other words Observable.from
can't know when the following chain completes. 换句话说,
Observable.from
无法知道以下链完成的时间。 It wouldn't even make sense because the Rx contract dictates that there's always only one complete
or error
notification. 它甚至没有意义,因为Rx合同规定总是只有一个
complete
或error
通知。 But if you used eg. 但是,如果你使用eg。
Observable.from().finally().share()
then you could have multiple subscribes and what would decide when the source Observable calls finally()
? Observable.from().finally().share()
然后你可以有多个订阅,什么决定源Observable调用finally()
? It can complete only once. 它只能完成一次。
Try to change the subscription logic and see whether you get what you are looking for 尝试更改订阅逻辑,看看你是否得到了你想要的东西
output.subscribe(
(x) => {console.log(x)},
error => console.error(error),
() => console.log('Finally I have really reached the END')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.