在等待后端响应时快速更改可观察状态



我正在尝试实现一个切换按钮,但我不知道如何使用Observables来处理这个特定的场景。为了防止用户点击和后端实际响应之间的延迟,我想我可以提前将其更改为新状态。然后,当后端有更新时,保持后端更新作为真相的来源。

在dom方面,我使用异步管道。

按钮组件侧:

this.isButtonActive$ = this.buttonService.isButtonActive$();

DOM端:

<span *ngIf="isButtonActive$ | async">
... 
</span>

来自服务方:

public isButtonActive$(): Observable<boolean> {
return this.currentState$.pipe(
map((state) => state.isActive)
);
}

一旦我从后端获得新的数据,它就会监听这个currentState$的更改并接收新的值。

但是,如果后端需要2-3秒的时间来更新,就会造成糟糕的用户体验。

这个想法是,用户一点击按钮,它就会立即将状态更改为新状态,无论目前是否失败,后端都会通知并相应更新。

如果这是承诺,对我来说很容易解决,但我如何用Observables管理这种行为?我是否被迫使用行为主题?

谢谢。

我不确定this.currentState$是如何填充的,但这里是我们为API调用尝试的。

public markActive() {
return this.http.post('myAPIURL', body).pipe(
startWith({
// object you want to set while API call is in progress.
});
);
}

https://www.learnrxjs.io/learn-rxjs/operators/combination/startwith

最新更新