Ngrx poll to update subscription data

Context

I use the following libraries in the corresponding application: Angular 4.x, ngrx 4.x, rxjs 5.4.x

In my application, I can get some data from websocket, but for some I have to click RESTful api. I share data between multiple components via ngrx. I am currently updating data based on events such as creation, update, and deletion.

I do not expect much data modification at the same time, but I need a way to manually or automatically verify that the status of my client matches the server. I would like to make optimistic updates that correct the state of the client, and not the cost of a complete update of the data on the corresponding state slice.

RxJs Approach

If I hadn’t used ngrx, I would probably just have a service that showed the observable, for example the next one, which would cache the last result of the api call and share it with all subscribers. He periodically updated the result, but only if he had subscribers.

const interval = 1000;
let counter = 0;

// setup a timer that executes immediately and on a timer
let call = Rx.Observable.timer(0, interval)
  // make the fake async call
  .switchMap(() => Rx.Observable.of(counter++).delay(100))
  .do(x => console.log('call', x))
  // cache latest value and share the value with all subscribers
  .publishReplay(1, interval)
  // only connect (aka make the call) if there are more than 1 subscribers
  .refCount();

// convenience method for simulation
function subscribe(name, take) {
  call.take(take).subscribe(
    x => { console.log(name, x); },
    null,
    () => { console.log(`${name} completed`) }
  );
}

// observers
subscribe('first', 1);
subscribe('second', 2);
window.setTimeout(() => {
  subscribe('third', 3);
}, 3500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.min.js"></script>
Run codeHide result

Problem

I'm not sure how I would simulate the same behavior with ngrx, since ngrx handles subscriptions for itself. In many ways, he disconnects the subscription from the source. Here are some ideas I described:

  • There may be a way that I could bite a punch store.select, but then I think that I will need to determine the explicit relationship between the effects and the state that are already defined in the gearboxes.
  • /, , , .
  • , ngrx - , , , .
  • .

ngrx , ?

+4
1

, , 100%. , - :

  • , , , (boolean)
  • , , , true
  • ngOnDestroy, false, .
  • ngrx, . true, , , . setInterval , , , .
  • false, ngrx , , /, / . , takeUntil
0

Source: https://habr.com/ru/post/1690142/


All Articles