Angular 4 caching

327 Views Asked by At

Problem:

  1. I have to display large amount of data

  2. Use pagination that can change count (user can select display 10 / 20 /50 per page)

  3. Was trying using rxjs following link https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html

  4. But I have 2 issues using this....

    4.1. This gives the latest data but I need to display data for that particular page and also display the same when I come back again

    4.2. I use a search on top which requires me to use the whole data but since this caching gets data in steps I will have issue when user searches before the complete data is pulled from the backend service...

Please suggest the best way to accommodate this issue....

1

There are 1 best solutions below

5
JBoothUA On BEST ANSWER

RXJS subjects have 3 different types of feeds, as far as

 1) if you miss it you miss it = Subject   
 2) give me the last value =  BehaviorSubject   
 3) give me all the last values = ReplaySubject

it sounds like you're looking for #3 correct? If so, just look into ReplaySubjects.

Subject - a subscriber will only get published values that were emitted after the subscription. A

BehaviorSubject - the last value is cached. An subscriber will get the latest value upon initial subscription.

ReplaySubject - it can cache up to a specified number of emissions. Any subscribers will get all the cached values upon subscription.

import * as Rx from "rxjs";

const subject = new Rx.ReplaySubject(2, 100);

// subscriber 1
subject.subscribe((data) => {
    console.log('Subscriber A:', data);
});

setInterval(() => subject.next(Math.random()), 200);

// subscriber 2
setTimeout(() => {
  subject.subscribe((data) => {
    console.log('Subscriber B:', data);
  });
}, 1000)

We create the ReplaySubject and specify that we only want to store the last 2 values, but no longer than a 100 ms We start emiting Subject values every 200 ms. Subscriber A will pick this up and log every value that’s being emited by the Subject. We start subscribing with Subscriber B, but we do that after 1000 ms. This means that 5 values have already been emitted by the Subject before we start subscribing. When we created the Subject we specified that we wanted to store max 2 values, but no longer then 100ms. This means that after a 1000 ms, when Subscriber B starts subscribing, it will only receive 1 value as the subject emits values every 200ms.