RxJS that emits the last value from one observable and then emits another true value

Hellow, I'm trying to create an observable (OBS) and subject (SUB) function that saves the last element from OBS, while SUB has the value F, and emit it (and only it) when the SUN becomes T

   OBS ---a----b----c----d----e----f----g----h-----
   SUB ------F----------T------------F-------T-----
   OUT -----------------c--------------------h-----

I tried to solve this problem with

OBS.window(SUB)
        .withLatestFrom(SUB)
        .switchMap(([window, status]) => {

            if(status === F) {
                return window.combineLatest(SUB, (cmd, status) => {
                    if(status === T) {
                        return null;
                    };

                    return cmd;
                }).last((e) => {
                    return !!e;
                })
            }

            return Observable.empty<Command>();
        }).filter((cmd) => {
            return !!cmd;
        })

but it does not work

+4
source share
2 answers

So it looks like you want something like:

SUB
  // Only emit changes in the status
  .distinctUntilChanged()
  // Only forward true values down stream
  .filter(t => t === T)
  // Only emit the latest from OBS when you get a T from SUB
  // Remap it so only cmd is forwarded
  .withLatestFrom(OBS, (_, cmd) => cmd)
+2
source

I found my own solution:

OBS
    .buffer(SUB)
    .withLatestFrom(SUB)
    .map(([buffer, t]) => {
        if(!buffer || !buffer.length) {
            return null;
        }

        if(t === T) {
            return buffer[buffer.length - 1];
        }

        return null;
    })
    .filter((e) => !!e);

this option has the following behavior

 ---a----b----c----d----e----f----g----h-----
 ------F----------T------------F-------T-----
 -----------------c--------------------h-----

and do not generate output if the window between F and T is empty

 ---a--------------d----e----f----g----h-----
 ------F----------T------------F-------T-----
 --------------------------------------h-----
+2
source

Source: https://habr.com/ru/post/1683446/


All Articles