D
D
Django Almighty2021-12-28 14:20:17
Angular
Django Almighty, 2021-12-28 14:20:17

How to properly cache each individual element via observable & shareReplay?

The situation is as follows: I get a list of all Observable elements and successfully cache it via shareReplay.
But I also have another getById(string id) method that should return one single element from all elements. Those. for this, we already have a cached observable of all elements. How to correctly display one element from the cache without making a call to the server?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2021-12-28
@12345678XYU87654321

1. Create a function for getting data,
myRequest = () => request.pipe(shareReplay(1));
2. create a variable of type four
list = myRequest();
This is your list of elements, when you subscribe to it, a request is executed and cached. At the next subscription, the cache is given.
3.

getById = (id) => list.pipe(map(_list => _list.find(filterById(id)))

a function that will return an observable with a search function hardwired into it.
For example
elementId1 = getById(1);
, when subscribing to elementId1, see point 2, and then search in the list.
When called getById(2), the same cache will be used.
If you ignore point 2 with writing the result of the call to a variable and call the function myRequestinside, then a second "cache" will be created and, accordingly, the second request. ____ can also be cached with your own so as not to look for a second time if we have two subscriptions to this element somewhere. getByIdmyRequest
getByIdshareReplay

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question