Angular service that returns observables/subjects from a cache array to multiple instances of a component in realtime

岁酱吖の 提交于 2019-12-06 05:05:48

You can only one Subject/Behaviour Subject. Return that as an observable which every UAC can subscribe to and listen for data. Now I am assuming there must be some unique identifier attached to every UAC, let's say a blog Id. So when you emit a data using Subject, along with data, append that blog Id as well in that data. In the UAC match if the UAC's id is the same as the id received from observable then update the data in UAC else ignore. This way the right UAC will be updated. For example:-

data.service.ts

const a = new BehaviourSubject();

getDataSource() {
 return a.asObservable():
}

cacheCheck(blogId: string) {
  // emit the data with a blogId.
  a.next({'id': blogId, 'data': getDataFromSomeWhere()})
}

blog.component.html

<app-uac [id]="blogId"></app-uac>

uac.component.ts

@Input id: string;
constructor(public dataService: DataService) {}
ngOnInit() {
   dataService.getDataSource().subscribe((data) => {
      if(data.id == this.id) //do somethin in UAC or emit event to parent
         //blog and let it do something
      else { //ignore}
   })
}

Something on this line.

Current Implementation:

Writing it down as it would be helpful for someone in the future. I managed to optimize it using observable pattern this way:

  • UAC onInit() calls dataService.getData(url,params,method,guid)
  • The guid passed by the UAC is the cache key for the service
  • UAC has two subscriptions from dataService. One is dataService.getData method that returns an observable - mainly used as an initializer to set guid - it unsubscribes after getting its first value using .pipe(first()). Second subscription is to a BehaviourSubject called dataChanged. Whenever data is changed on dataService cache, it emits dataChanged.next(newDataDelta). This subscription persists till the component's onDestroy.
  • dataService checks hierarchically as cache[guid] > storage[guid] > http[url], sets data accordingly, and finally calls dataChangedSubj.next(cache[guid]) Only the changed delta would be emitted
  • All UACs receive the new cached DataSet (which is cache[guid]; contains only what was changed) and checks for receivedData[guid] to see if the emitted data is relevant to the UAC. If yes, it consumes it.
  • If user up-votes/down-votes on a UAC, UAC does necessary API calls, and on success, does dataService.updateData(guid,data), which in-turn emits the change using dataChanged.next(newDataDelta) to all UACs and the UACs that belong to the same blog post would update its data (as they would have the same guid)

Still open for the best way to implement this use case using RxJS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!