Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - How to start second observable *only* after first is *completely* done in rxjs

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 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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$
    );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...