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

问题描述

我的印象是 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$
    )

mkdir 尝试(和失败)创建 ./some_dir rimraf 完成之前删除目录。但是,在投掷结束时, ./ 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?

推荐答案

问题是创建一个函数,在调用时执行底层函数并通过 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中首先*完全*完成后才启动第二个observable * *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:40