简体   繁体   English

如何在 concat 运算符完成后执行代码

[英]How to execute code after concat operator finish

I have tasks (observables) in array and want run them sequentially and at the end I want to run some finish code我在数组中有任务(可观察到的)并希望按顺序运行它们,最后我想运行一些完成代码

 const { concat, of, tap } = rxjs; const { delay } = rxjs.operators; let tasks = [ of(1).pipe(delay(1000)), of(2).pipe(delay(2000)), of(3).pipe(delay(1000)), of(4).pipe(delay(2000)), ]; // In below example, word "Finish" is printed 4 times // but I want print it only once, at the end. concat(...tasks).pipe(tap(()=> console.log('Finish'))).subscribe(n => console.log(`result for task ${n}`));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.0/rxjs.umd.min.js" integrity="sha512-v0/YVjBcbjLN6scjmmJN+h86koeB7JhY4/2YeyA5l+rTdtKLv0VbDBNJ32rxJpsaW1QGMd1Z16lsLOSGI38Rbg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

I try to use tap but without success - how to do it?我尝试使用tap但没有成功 - 怎么办?

Tap, how you use, will run on each emited value.点击,你如何使用,将运行在每个发出的值上。

You should use finalize instead.您应该改用finalize

 const { concat, of, finalize } = rxjs; const { delay } = rxjs.operators; let tasks = [ of(1).pipe(delay(1000)), of(2).pipe(delay(2000)), of(3).pipe(delay(1000)), of(4).pipe(delay(2000)), ]; concat(...tasks).pipe(finalize(()=> console.log('Finish'))).subscribe(n => console.log(`result for task ${n}`));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.0/rxjs.umd.min.js" integrity="sha512-v0/YVjBcbjLN6scjmmJN+h86koeB7JhY4/2YeyA5l+rTdtKLv0VbDBNJ32rxJpsaW1QGMd1Z16lsLOSGI38Rbg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM