Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous value of RxJS Subject?

I my project I need to compare my paginator's pageSize value (items per page) with the previous value and if the new one is higher, then I need to load datas from storage. But if it's not higher I don't want to do anything.

For example in this code:

export class MyComponent {
  paginatorPageSize: BehaviorSubject<number> = new BehaviorSubject<number>(10);
  // ...

  savePageSettings() {
    this.pageService.save().pipe(
      map((result: any) => {
        // ...
      }),
      tap(() => this.anyCode.here()),
      switchMap((result: any) => {
        // ...
      }),
      switchMap(() => {
        const previousPageSize = ??? // <--- here how can I get the prevoius value of paginatorPageSize?

        if (previousPageSize >= this.paginatorPageSize.value) {
          return this.pageService.getAll();
        }

        return of(null)
      })
    ).subscribe();
  }
}

Is there any way to get the previous emitted value of a RxJS Subject / BehavioSubject or any kind of subjects?

like image 843
netdjw Avatar asked Jul 23 '20 13:07

netdjw


1 Answers

just use pairwise operator.

savePageSettings() {
    this.pageService.save().pipe(
      map((result: any) => {
        // ...
      }),
      tap(() => this.anyCode.here()),
      switchMap((result: any) => {
        // ...
      }),
      pairwise(),
      switchMap(([oldResult, newResult]) => {
        const previousPageSize = oldResult.pageSize;

        if (previousPageSize >= this.paginatorPageSize.value) {
          return this.pageService.getAll();
        }

        return of(null)
      })
    ).subscribe();
  }
like image 148
bubbles Avatar answered Sep 16 '22 22:09

bubbles