[英]Using takeUntil to complete an RxJS stream
I want to complete an inner stream that doesn't naturally complete, using the takeUntil
operator, like this: 我想使用
takeUntil
运算符来完成无法自然完成的内部流,如下所示:
outerObservable
.mergeMap(() => {
innerObservable
.takeUntil(stopObservable$)
});
This works, the inner stream completes as expected, but I would like for the outer stream to return one last value after the stop signal. 这可以正常工作,内部流按预期完成,但是我希望外部流在停止信号之后返回最后一个值。 Even after lots of googling, I still don't know how.
即使经过大量谷歌搜索,我仍然不知道如何做。
EDIT: 编辑:
I've written an operator that seems to do the trick, but leaving the question open because I know there's a better way or something I'm completely misunderstanding. 我写了一个似乎可以解决问题的运算符,但是让问题悬而未决,因为我知道有更好的方法或完全被我误解的东西。
function takeUntilThen(notifier, oneLastValue) { return Rx.Observable.create(subscriber => { var source = this; notifier.subscribe(() => { subscriber.next(oneLastValue); subscriber.complete() }); return source.subscribe(value => { subscriber.next(value); }, err => subscriber.error(err), () => subscriber.complete()); }); }
Sounds like you want to race between innerObservable
and stopObservable
and Whichever wins, should be able to output something . 听起来您想在
innerObservable
和stopObservable
之间innerObservable
,无论哪个获胜,都应该能够输出一些东西 。
You can use the aptly named .race()
operator for this, instead of using .takeUntil()
. 您可以
.race()
使用适当命名的.race()
运算符,而不是使用.takeUntil()
。 See the example in the redux-observable docs recipe on Cancellation: 请参阅关于取消的redux-observable docs食谱中的示例:
https://redux-observable.js.org/docs/recipes/Cancellation.html#cancel-and-do-something-else-eg-emit-a-different-action https://redux-observable.js.org/docs/recipes/Cancellation.html#cancel-and-do-something-else-eg-emit-a-different-action
const somethingEpic = action$ =>
action$.ofType(SOMETHING)
.mergeMap(action =>
innerObservable
.race(
stopObservable
.take(1)
)
);
Since your example is pseudo code, here's one that's more concrete: 由于您的示例是伪代码,因此以下是更具体的示例:
import { ajax } from 'rxjs/observable/dom/ajax';
const fetchUserEpic = action$ =>
action$.ofType(FETCH_USER)
.mergeMap(action =>
ajax.getJSON(`/api/users/${action.payload}`)
.map(response => fetchUserFulfilled(response))
.race(
action$.ofType(FETCH_USER_CANCELLED)
.map(() => incrementCounter())
.take(1)
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.