Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJs `sample` operator multiple times

In RxJS, when you need to combine two Observables and emit only when one of those emits, you use withLatestFrom

source$.pipe(
  withLatestFrom(other$),
  map(([sourceValue, otherValue]) => ...) // this is only executed when `source$` has new values, regardless of `other$` emission
)

If source$ emits multiple times but other$ don't, you always get the same, latest, value and do execute map.

If you don't need the value of the "signalling" stream, you can use sample.

interestingStream$.pipe(
  sample(signallingStream$),
  map((interestingValue) => ...) // this function does not receive `signallingStream$`'s values
)

However, map is only executed if signallingStream$ emits after interestingStream$ emitted a new value; no value is emitted twice downstream.

So my question is, is there an operator, a combination of operators, or something else that allows me to get multiple times the latest value of a source stream without forcing me to get and ignore the value of a signalling stream like in the following snippet?

signallingStream$.pipe(
  withLatestFrom(interestingStream$),
  map(([_ignore_, interestingValue]) => interestingValue),
)
like image 976
technicated Avatar asked Dec 22 '25 15:12

technicated


1 Answers

I guess you could use something like the following:

const shared$ = interestingStream$.pipe(
  publishReplay(1),
);

const source = signallingStream$.pipe(
  concatMapTo(shared$.pipe(take(1))),
);

shared$.connect();

publishReplay() should keep a single instance of ReplaySubject() so every time you subscribe to it it'll reemit the latest value from interestingStream$ By calling connect() you make the Observable "hot".

Live demo: https://stackblitz.com/edit/rxjs-ewew2n

like image 64
martin Avatar answered Dec 24 '25 03:12

martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!