Rxjs - only the first observer can see data from observable.share()

混江龙づ霸主 提交于 2019-12-10 18:32:39

问题


I have some code snippet as following

var videosNeedFix = Rx.Observable.fromArray(JSON.parse(fs.readFileSync("videoEntries.json"))).share();

videosNeedFix.count().subscribe(function(count){ //subscrption A
  console.log(count + " in total"); 
});


videosNeedFix.subscribe(function(videoEntry){ //subscription B
  console.log(videoEntry.id, videoEntry.name, videoEntry.customFields); 
});

The videoEntries.json is a JSON-serialized array of videoEntry object. I'm expecting both subscription A and subscription B to receive the data emitted by videosNeedFix observable.

However, according to the console log, only the subscription A will receive data but not the subscriptionB. If I swap the order of making the two subscriptions, only subscriptionB will see the data. How come the observable only emits data to the first subscription?


回答1:


This is a good use case (and maybe the only - see To Use Subject Or Not To Use Subject?) for a Rx.Subject

Consider the following example. This code (with .delay() hack mentioned in the comments) will work, but seems a bit hacky to me:

  let stream$ = Rx.Observable
        .return(updatesObj)
        .map(obj => Object.assign({}, obj.localData, obj.updates))
        .delay(1) //Hacky way of making it work
        .share()

    stream$
        .flatMap(obj => Observable.fromPromise(AsyncStorage.setItem('items', JSON.stringify(obj))))
        .catch(Observable.return(false))
        .subscribe()

      stream$
        .subscribe(obj =>  dispatch(dataIsReady(obj)))

Example with Rx.Subjects:

  let subjS = new Rx.Subject()

  let stream$ = subjS
    .map(obj => Object.assign({}, obj.localData, obj.updates))
    .share()

  stream$
    .flatMap(obj => Observable.fromPromise(AsyncStorage.setItem('items', JSON.stringify(obj))))
    .catch(Observable.return(false))
    .subscribe()

  stream$
    .subscribe(obj =>  dispatch(dataIsReady(obj)))

  subjS.onNext(updatesObj)


来源:https://stackoverflow.com/questions/25634375/rxjs-only-the-first-observer-can-see-data-from-observable-share

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