Search code examples
rxjsrxjs-observablesrxjs-pipeable-operators

RxJs skip sampleTime on startWith value


I want to skip the sampleTime on the startWith value. The Observable should emit false instantly and only then use sampleTime.

I want the Observable to emit booleans. On click of a loading button a Loadingspinner should be displayed until the data is delivered, but at least for one second. The data$ Observable instantly emits null and then eventually the requested data.

showLoadingSpinner$ = this.data$.pipe(
  map(x => x == null),
  sampleTime(1000),
  startWith(false),
)

How can I do this? Should i use a different operator?


Solution

  • Ok So you can use concat, where the observable will be executed sequentially, first we create an observable that takes only the first value without sampleTime, then after that completes due to take we will go to the second observable where we have sampleTime

    const data$ = rxjs.interval(1000);
    let first = true;
    showLoadingSpinner$ = rxjs.concat(
      data$.pipe(rxjs.take(1)), // first
      data$.pipe(rxjs.sampleTime(2000)) // second
    ).pipe(
      rxjs.map(x => x == null),
      rxjs.startWith(false),
    ).subscribe(console.log)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.6.0/rxjs.umd.min.js" integrity="sha512-  ejsljG9xAKvLl8gCL5FQmGLQ5dZvr2g9n7iwBYG3bIAmfPwjA4P2tX6lvvj2ry+cUpmiuBaF70F3Y5/6o/KrPQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>