简体   繁体   中英

RxJS need shareReplay with default value

The problem is that startWith and shareReplay combine poorly.

If you use source.startWith(0).shareReplay(1) , new subscriptions will always start with 0 , and shareReplay is meaningless, source.shareReplay(1).startWith(0) works slightly better, but result in new subscriptions to receive two values.

Expected:

source ---1---2----3---4----5
ob1    0--1---2----3---4----5
ob2             2--3---4----5

Update: Seems like my minimized case was too minimized. My problem is that i switch from ob1 to ob2 using switch , what means ob1 will unsubscribe right before ob2 subscribes. Weirdly enough it does work correctly if i use just shareReplay(1) , but the combination of startWith(0).shareReplay(1) does not.

const main$ = new Rx.Subject()
const s1$ = new Rx.Subject()


// Expected:
// 0 1 2 2 3 4

//const s2$ = s1$.shareReplay(1).startWith(0)
// got: 
// 0 1 2 0 2 3 4

//const s2$ = s1$.startWith(0).shareReplay(1)
// got:
// 0 1 2 2 0 3 4

const s2$ = s1$.shareReplay(1)
// got:
// 1 2 2 3 4

main$.switch()
  .subscribe(
    v => console.log("1: " + v)
  )

main$.onNext(s2$)
s1$.onNext(1)
s1$.onNext(2)

main$.onNext(s2$)

s1$.onNext(3)
s1$.onNext(4)

I could not reproduce your problem, I put up a jsfiddle: cf. http://jsfiddle.net/qvb3xbqz/2/ .

var counter = 0;
 var validation$ = Rx.Observable
 .fromEvent(document.getElementById('validation'), 'click')
 .map(function(){return ++counter})
 .do(emits(ta_validation, 'First subscription'))
 .startWith(0)
 .shareReplay(1);

setTimeout(function (){
  validation$.do(emits(ta_change, 'second subscription')).subscribe(function(){})
}, 1000);

One subscription is immediately subscribed. Second subscription kicks in after 1s. You will see that they behave as expected. Or did I misunderstand something?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM