Rxjs - only the first observer can see data from o

2019-07-07 01:42发布

问题:

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)