简体   繁体   中英

RXJS Repeat latest Value of Observable on Emitted Value of another Observable

i am currently looking for an easier solution for the following Problem:

I want to repeat the latest value of an observable as soon as the application emits a truethy ready state. Is there an easier way without creating an extra temporary Subject like in the following solution using the rxjs operators? I could not create a working combination with those.

Current Solution without rxjs operators:

private repeatWhenReady<T>(obs: Observable<T>): Observable<T> {
  // store.select returns the observable of the ready State
  const readyObs = this.store.select(state => state.ready).pipe(first(ready => ready=== true));
  const resultSubject = new Subject<T>();
  let lastValue: T;
  let lastValueSet = false;
  let ready = false;
  const complete = () => resultSubject.complete();

  obs.subscribe((value) => {
    if (!ready) {
      lastValue = value;
      lastValueSet = true;
    } else {
      resultSubject.next(value);
    }
  }, complete, complete);

  readyObs.subscribe(() => {
    ready = true;
    if (lastValueSet) {
      resultSubject.next(lastValue);
    }
  });

  return resultSubject.asObservable();
}

You can try with withLatestFrom operator.

private repeatWhenReady<T>(obs: Observable<T>): Observable<T> {
  return this.store.select(state => state.ready)
.pipe(
first(ready => !!ready), // filter your ready value with true
withLatestFrom(obs),  // take last value of your observable
map(([first, second]) => { // map observable pipe to second value 
    return second;
  })
);
}

You can access here.

[https://www.learnrxjs.io/learn-rxjs/operators/combination/withlatestfrom][1]

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