简体   繁体   中英

RxJS: How does shareReplay not store null values ?

let btn = document.getElementById('btn')
let input = document.getElementById('input')

let input$ = defer(() => of(input.value)).pipe(
  tap(v => console.log('tap', v)),
  filter(v => v),
  shareReplay(1)
)
let click$ = fromEvent(btn, 'click').pipe(
  switchMap(_ => input$)
)
click$.subscribe(v => console.log(v))

I just want to store input$ when input value not null. The problem now is that if the input value is null at first, it already store, filter not work.
demoLink

You can try this, make a if-else before the input$

let btn = document.getElementById('btn')
let input = document.getElementById('input')
if (input != null){
  let inputValue = input
}

let input$ = defer(() => of(inputValue.value)).pipe(
  tap(v => console.log('tap', v)),
  filter(v => v),
  shareReplay(1)
)
let click$ = fromEvent(btn, 'click').pipe(
  switchMap(_ => input$)
)
click$.subscribe(v => console.log(v))

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