Usman Ahmad
Usman Ahmad

Reputation: 41

subscribing mobx @observable using rxjs Observable but not getting on change in a deep level component (ts file)

i am trying to get change from angular-mobx store using rxjs observable. but not getting any change from there, if observed array changed. But if i assign new value using '=' sign then i got change in subscribe. Anyone can explain it ? or help to get change by only change like splice or replace object in array ? thanks

https://stackblitz.com/edit/angular-reuych DEMO APP

import { computed, action, observable } from "mobx-angular";
import {observe  } from "mobx";
import { Observable } from 'rxjs';
import { Injectable } from "@angular/core";
import * as moment from "moment-timezone";
@Injectable()
export class Store {toRx(obj, prop) {
   return Observable.create(observer =>
      observe(obj, prop, (change) => observer.next(change.newValue), true)
    );
  }
  @observable storeCampaigns:any=[];

}

then in a component subscribing like this

this.store.toRx(this.store.storeCampaigns, 'campaigns')
  .subscribe(val =>  {
  console.log("calendar get change", val)

Upvotes: 0

Views: 1205

Answers (1)

If you dive deeper in mobx you will get to the following link observer where you can find the following comment

/**
 * A node in the state dependency root that observes other nodes, and can be observed itself.
 *
 * ComputedValue will remember the result of the computation for the duration of the batch, or
 * while being observed.
 *
 * During this time it will recompute only when one of its direct dependencies changed,
 * but only when it is being accessed with `ComputedValue.get()`.
 *
 * Implementation description:
 * 1. First time it's being accessed it will compute and remember result
 *    give back remembered result until 2. happens
 * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3.
 * 3. When it's being accessed, recompute if any shallow dependency changed.
 *    if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step.
 *    go to step 2. either way
 *
 * If at any point it's outside batch and it isn't observed: reset everything and go to 1.
 */

Which pretty much states that a new value will be computed (i.e.. new thing will come trough the subscription) only when the value is accessed for the first time (i.e. when you subscribe) or when there are dependency changes (i.e. when you change the stored refs, in your case with the = operator inside the store).

So if I have to do a summary that is just the way it works, the behavior is quite similar to other state management libraries, which are pushing new values to their subscribers only when some of the refs inside the store are changed.

** Disclaimer, not a mobx pro, but that's what the source code says.

Upvotes: 1

Related Questions