在继续执行下一个代码之前,确保可观察到的订阅完成 [英] Guarantee observable subscription finishes before proceeding to next code
问题描述
我正在通过多个服务调用进行级联删除.某些更高版本的订阅依赖于先前的订阅来完成.我该如何保证订阅完成才能进入下一个代码?
I am doing a bit of a cascade delete with multiple service calls. Some of the later subscriptions rely on previous subscriptions to finish. How can I guarantee an subscription finishes before moving onto my next code?
// Need to make sure this code completes
data.forEach(element => {
this.myService.delete(element.id).subscribe();
});
// Before running this code
this.myService.getAll().subscribe(res => {
res.data.forEach(element => {
this.myService.delete(element.id).subscribe();
});
}
);
推荐答案
Subscription
具有一个单一目的:处置,但是您可以选择:
A Subscription
has a singular purposes: disposing, but you have options:
-
如果您要一个又一个地订阅可观察的数据,可以使用
concat
.
如果要同时订阅多个可观察对象并合并每个对象的最后一个值,则可以使用
If you want to subscribe to multiple observables at the same time and combine the last value of each, you can use forkJoin
.
如果要在另一个可观测值中使用一个观测值的屈服值,则可以使用flatMap
.
If you want to use yielded value of an observable in another observable, you can use flatMap
.
import { forkJoin, interval, concat, of } from "rxjs";
import { first, flatMap } from "rxjs/operators";
var combinedIntervals =
forkJoin(
interval(1000).pipe(first()),
interval(2500).pipe(first())
).pipe(
flatMap(([a, b]) => of(`${a} and ${b}`))
);
concat(
combinedIntervals,
of("after both intervals")
)
.subscribe(
console.log.bind(console)
);
// 0 and 0
// after both intervals
对于您的特定情况,您将选择删除操作作为可观察对象,然后forkJoin加入它们.
For you specific case, you'd select your delete operations as observables and then forkJoin them.
var data = [];
var obsBatch1 = data.map(element => myService.delete(element.id));
var obsBatch2 =
forkJoin(
obsBatch1,
elements => elements.map(
element => myService.delete(element.id)
)
);
obsBatch2.subscribe();
这是rxjs@6
语法.我将rxjs@5
留作练习.
This is rxjs@6
syntax. I leave rxjs@5
as an exercise.
这篇关于在继续执行下一个代码之前,确保可观察到的订阅完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!