gpt4 book ai didi

javascript - 在 Rxjs 中如何暂停一个数据流并从第二个继续它被暂停了?

转载 作者:行者123 更新时间:2023-12-03 07:10:00 26 4
gpt4 key购买 nike

我有一个数据流每 10 秒被长时间轮询一次。长pol可以是暂停 并成为 .
问题是 : 当它继续时它会重新开始。我必须让它从第二个继续它被暂停。
因此,如果:
延迟(10000)
暂停在 (7000)
然后,当我再次开始长轮询时,我的数据必须在 (10000-7000)= 之后提取。 3000
今天是第四天我一直被这个问题困住并且发疯了..
我创造了这个 Blitz
https://stackblitz.com/edit/ang7-working-rxjs-stream-timer-combined?file=src/app/app.component.ts
创建了一个流和一个提取数据的计时器。当流和计时器停止时,设置剩余的时间以及新的延迟。但是当我按下开始时它不会再等待 3 秒它只是立即调用我不想要的服务

最佳答案

这是一个非常基本的实现,依赖于 timer功能和take , filtertakeUntil运营商。
在我看来,解决方案不太优雅。它取决于状态变量 pausedfirst并且在 next 中有一个递归触发器订阅中的回调。另请注意,它目前不进行任何错误处理。在这种情况下,轮询完全停止。
Controller

export const REFRESH_INTERVAL = 11;

@Component({ ... })
export class AppComponent implements OnDestroy {
pause$ = new Subject();
reset$ = new Subject();
closed$ = new Subject();
counter = REFRESH_INTERVAL;
res: any;
paused = false;

constructor(private freeApiService: freeApiService) {}

ngOnInit() {
this.init();
}

init() {
let first = true;
this.reset$
.pipe(
switchMap(_ =>
timer(0, 1000).pipe(
take(this.counter),
tap(_ => (this.paused = this.paused ? false : this.paused)),
takeUntil(this.pause$),
filter(_ => first || --this.counter === 0),
finalize(
() => (this.paused = this.counter != 0 ? true : this.paused)
),
switchMap(_ => this.freeApiService.getDummy())
)
),
takeUntil(this.closed$)
)
.subscribe({
next: res => {
first = false;
this.res = res;
this.counter = REFRESH_INTERVAL;
this.reset$.next();
},
error: error => console.log("Error fethcing data:", error)
});
}

ngOnDestroy() {
this.closed$.next();
}
}
模板
<div my-app>
<ng-container *ngIf="res; else noRes">
<button (mouseup)="paused ? reset$.next() : pause$.next()">
{{ paused ? 'Resume poll' : 'Pause poll' }}
</button>

<br><br>
Refreshing in: {{ counter }}
<br>
Response:
<pre>{{ res | json }}</pre>
</ng-container>

<ng-template #noRes>
<button (mouseup)="reset$.next()">
Start poll
</button>
</ng-template>
</div>
我修改了你的 Stackblitz

关于javascript - 在 Rxjs 中如何暂停一个数据流并从第二个继续它被暂停了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64711926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com