我想每5秒重复一次我的forkJoin方法。一旦forkJoin完成并返回结果,就应该启动5秒计时器;
这是我现在的forkJoin:
let getResult1 = this.myService.GetResult1(param1, param2); // retrun Observable<Result1>
let getResult2 = this.myService.GetResult2(param1, param3,param4);// retrun Observable<Result2>
Observable.forkJoin(getResult1, getResult2)
.subscribe(results => {
this.result1 = results[0];
this.result2 = results[1];
.. start counting 5 seconds and then repeat this again and again
},
error => this.handleError(error));
我想要的时间线:
时间:0--1--2--3--4--5-6
行动: Req - Res
等待:等待5秒
发布于 2017-10-27 12:42:37
我不确定这是不是最优雅的方式。具有更多rxjs经验的人可能能够提供一个更干净的解决方案,但我的第一个想法是使用一个主题来确定何时调用forkJoin。然后,只需在forkJoin之后添加一个计时器就可以发出另一个请求。
// component.ts
subject$: Subject = new Subject();
ngOnInit(){
this.subjectSubscription = this.subject$
.flatMap(res => {
return Observable.forkJoin(
this.dummy1$, // dummy observable api
this.dummy2$ // dummy observable api
);
})
.subscribe(res => {
// after 5 seconds, call subject.next to fire another forkJoin call
this.timerSubscription = Observable.timer(5000).subscribe(res => {
this.subject$.next();
})
});
// make initial call
this.subject$.next();
}
下面是一个演示plnkr (https://plnkr.co/edit/OaLIMxKKUqNXxcGp0HLW?p=preview),包括订阅清理,以避免内存泄漏
发布于 2017-10-27 12:35:19
使用可以观察到的间隔:
Observable.interval(5000)
.switchMap(t =>
Observable.forkJoin(getResult1, getResult2))
.subscribe(results => {
this.result1 = results[0];
this.result2 = results[1];
},
error => this.handleError(error));
这将每5秒生成一个请求,而不一定是在完成后5秒。但应该足够近了。如果只需要5秒,你就需要一种不同的方法。
发布于 2020-02-28 03:31:30
在完成回调方法内部的代码后使用setTimeout
。
export class MyComponent {
private refreshInterval: number;
private timeoutId: any;
public ngOnInit(): void {
this.refreshInterval = 5000; // 5 seconds.
this.refresh();
}
private refresh(): void {
forkJoin(
this.service1.doThis(),
this.service2.doThat(),
// More calls...
).subscribe(results => {
this.data1 = results[0];
this.data2 = results[1];
// More stuff...
this.timeoutId = setTimeout(() => this.refresh(), this.refreshInterval);
});
}
public ngOnDestroy(): void {
if (this.timeoutId) clearTimeout(this.timeoutId);
}
}
https://stackoverflow.com/questions/46982316
复制相似问题