简体   繁体   中英

Get latest 2 values from status in rxjs store

I need to keep track for the changes on the latest id on the store, so I need to get the value before the change and after the change.

 this.store.select(currentSearchSelector).subscribe(search => {
      this.currentSearchId = search.id;
      console.log('current ' + this.currentSearchId);
      // I need to detect the change on this id in the store
    });

What is the right thing to keep an eye on the latest change without loosing the previous change?

Eg: if the currentSearchID = 21 then change to 22 I need to detect this change. On the subscription I had, the listner will keep getting the latest change only.

Thank you for your question!

I think you could use the bufferCount operator with the value of 2.

It will create an observable that will emit values only when the buffer is full and emits the values as an array . To find more info you can check the official documentation .

PS The size of the buffer should be 2 in your case.

this.store.select(currentSearchSelector)
    .pipe(bufferCount(2))
    .subscribe(([previousSearch, currentSearch]) => {
       this.currentSearchId = currentSearch.id;
       console.log('current ' + this.currentSearchId);
       console.log('previous ' + previousSearch.id);
    });

Also, there is an example with the bufferCount operator StackBlitz

Update

The pairwise operator is a more specific version of bufferCount that just emits the last two items together and is probably more appropriate here.

Whichever you choose you probably also need to couple it with a filter operator to check for the change in the search ID.

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