如何在rxjs中*完全*完成第一个*之后*仅*启动第二个可观察对象 [英] How to start second observable *only* after first is *completely* done in rxjs

查看:15
本文介绍了如何在rxjs中*完全*完成第一个*之后*仅*启动第二个可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是 Observable.[prototype.]concat 确保第一个操作在第二个操作开始之前完全完成.但在以下代码中:

I was under impression that Observable.[prototype.]concat makes sure first operation is fully finished before second operation starts. But in following code:

Observable
    .concat(
        Observable.fromNodeCallback(rimraf)(path.resolve('./some_dir')),
        Observable.fromNodeCallback(mkdir)(path.resolve('./some_dir')),
        writeToSomeDir$
    )

mkdirrimraf 完成删除目录之前尝试(但失败)创建 ./some_dir.然而,在(抛出)结束时,./some_dir 最终被删除.

mkdir attempts (and fails) to create ./some_dir before rimraf is finished deleting the dir. At the end (of throwing) however, ./some_dir ends up getting deleted.

为什么 Observable.concat 会显示这种行为?如何确保第一个 Observable 在开始第二个 Observable 之前完全完成而不会落入 rimraf 的同步版本?

Why is Observable.concat showing such behaviour? How can I make sure first Observable is fully finished before starting with second Observable without falling to sync version of rimraf?

推荐答案

问题在于 fromNodeCallback 创建一个函数,该函数在调用时执行底层函数并通过 Observable.本质上,Observable 返回值正在替换您通常必须作为最后一个参数传递给函数的节点样式回调.但是,该函数仍然会立即被调用.

The problem is that fromNodeCallback creates a function that when invoked executes the underlying function and returns the result of the invocation through an Observable. Essentially the Observable return value is replacing the node style callback you would normally have to pass as the last argument to the function. However, the function still gets invoked immediately.

如果您想延迟方法的执行,您可以将它们包装在 defer 中以防止它们执行,直到订阅 Observables.

If you want to delay the execution of the methods you can wrap them in defer to prevent their execution until the Observables are subscribed to.

var rimrafObservable = Observable.fromNodeCallback(rimraf);
var mkdirObservable = Observable.fromNodeCallback(mkdir);

Observable
    .concat(
        Observable.defer(() => rimrafObservable(path.resolve('./some_dir'))),
        Observable.defer(() => mkdirObservable(path.resolve('./some_dir'))),
        writeToSomeDir$
    );

这篇关于如何在rxjs中*完全*完成第一个*之后*仅*启动第二个可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆