我有一个 Angular 应用程序,应该在某些条件下(软件中的某些触发器或用户请求时触发)与服务器同步一些数据。所以我有一个这样的函数:
...
public createSyncObservable(): Observable<any> {
return this.retriveDataFromStorage().pipe(
switchMap(
(data) => forkJoin(this.api.sendData1(data.data1),this.api.sendData2(data.data2),this.api.sendData3(data.data3))
),
switchMap(
(data) => this.api.getDataFromServer()
),
switchMap(
(data) => this.updateLocal(data)
)
)
}
我想要的行为是:
- 如果用户(或某些触发器)请求同步并且它已经发生,我不应该再这样做,只需等待当前同步结束并返回相同的可观察值(共享)。
- 如果上次同步已经完成,它应该重新开始(创建一个新的可观察值)。
我现在最好的解决方案是做这样的事情(未经测试的代码):
...
public syncData(): Observable<any> {
if (this.observable_complete) {
this.observable_complete = false;
this.syncObservable$ = this.createSyncObservable().pipe(share())
this.syncObservable$.subscribe(
(data) => {this.observable_complete = true}
)
}
return this.syncObservable$;
}
这是要走的路吗?也许我缺少一些在这种情况下可以帮助我的 RxJS 运算符?这个解决方案看起来有点老套......
最佳答案
如果调用 this.createSyncObservable()
不执行任何实际工作,而只是订阅它返回的可观察对象,那么您只需要调用该函数一次。然后您可以简单地执行以下操作:
public syncData$ = this.createSyncObservable().pipe(share());
如果没有订阅者(即当 this.createSyncObservable()
完成时),share
将从其源取消订阅。因此,this.syncData$
的订阅者将触发对从 this.createSyncObservable()
返回的 observable 的订阅(如果完成)。
// The first subscribe will trigger a subscribe to createSyncObservable()
syncData$.subscribe()
// A second subscribe while the first hasn't completed won't trigger a subscribe
// to createSyncObservable() but instead just wait for its response
syncData$.subscribe()
// After some time ...
// Another subscribe after createSyncObservable() completed will trigger another
// subscribe to createSyncObservable()
syncData$.subscribe()
关于angular - 如果可观察未完成,则共享订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63845774/