mobx icon indicating copy to clipboard operation
mobx copied to clipboard

Chaining asynchronous calls

Open ptomask opened this issue 9 years ago • 11 comments

Greetings. For some time I struggle a bit with implementing chain of asynchronous calls. Look at this:

class AsyncChain {
  @observable param1;
  @observable param2;
  @observable param3;

  @observable resultA;
  @observable resultB;

  constructor() {
    this.ar1 = autorun(() => {
      asyncCallA(this.param1, this.param2)
      .then(result => this.resultA = result);
    });

    this.ar2 = autorun(() => {
      asyncCallB(this.param1, this.param3, this.resultA)
      .then(result => this.resultB = result)
    })
  }
}

const ac = new AsyncChain();

ac.param2 = 1; // Triggers asyncCallA, which will trigger asyncCallB when resolved.
ac.param3 = 2; // Triggers asyncCallB
ac.param1 = 3; // Triggers both async calls and asyncCallB is triggered once again when asyncCallA resolves.

This behaves as expected. But intent is to let asyncCallB wait for asyncCallA resolution when param1 is changed, because it invalidates resultA value. The simplest solution can be this:

class AsyncChain {
  @observable param1;
  @observable param2;
  @observable param3;

  @observable resultA;
  @observable resultB;

  constructor() {
    //AR1
    this.ar1 = autorun(() => {
      asyncCallA(this.param1, this.param2)
      .then(result => this.resultA = result);
    });
    
    //AR2
    this.ar2 = autorun(() => {
      asyncCallB(untracked(() => this.param1), this.param3, this.resultA)
      .then(result => this.resultB = result)
    })
  }
}

const ac = new AsyncChain();

ac.param2 = 1; // Triggers asyncCallA, which will trigger asyncCallB when resolved.
ac.param3 = 2; // Triggers asyncCallB
ac.param1 = 3; // Triggers asyncCallA, which will trigger asyncCallB when resolved.

This is nice - Triggering of AR2 is no consequence of changing param1. But what if param1 becomes unobserved in AR1 - e.g. by calling ac.ar1()? Then I need to make param1 tracked in AR2. In this case I can imagine a solution using reaction - something like this:

class AsyncChain {
  @observable param1;
  @observable param2;
  @observable param3;

  @observable resultA;
  @observable resultB;

  @bTracksParam1 = false;

  constructor() {
    //AR1
    this.ar1 = autorun(() => {
      asyncCallA(this.param1, this.param2)
      .then(result => this.resultA = result);
    });
    
    //AR2
    this.ar2 = reaction(
      () => {
        return {
          param1: this.bTracksParam1 ? this.param1 : untracked(() => this.param1),
          param3: this.param3,
          resultA: this.resultA,
        }
      },
      () => {
        asyncCallB(this.param1, this.param3, this.resultA)
        .then(result => this.resultB = result)
      },
      {
        compareStructural: true,
        fireImmediately: true,
      }
    )
  }
}

But still the AR2 reaction needs to know, that sometimes resultA is dependent on param1 but sometimes not. What if resultA is not directly set by asyncCallA but is some computed value? It has to be manually decided when bTracksParam1 should be set true or false.

Another problem is when param1 is changed and asyncCallA returns the same result as before, so none of variables tracked by AR2 changes, but still AR2 needs to run, because it depends on param1... This could be solved by setting resultA to some value, saying "resultA is no longer valid" right at the beginning of AR1 and adding a condition testing this to AR2 so it only runs when resultA is valid.

I still feel that there has to be a different approach, which avoids mentioned problems in some different and elegant way, is there?

ptomask avatar Sep 30 '17 05:09 ptomask

I think you could do something like:

// updates resultA and resultB on a change of param1, param2
autorun(() => {
  asyncCallA(this.param1, this.param2)  
  .then(action(resultA => this.resultA = resultA))     
  .then(() => asyncCallB(this.param1, this.param3, this.resultA))        
  .then(action(resultB => this.resultB = resultB));
});
// updates resultB on a change of param3
reaction(() => this.param3, () => asyncCallB(this.param1, this.param3, this.resultA));

However it's not much better.

The problem lies in depedency graph I believe: resultA depends on param1, param2
resultB depends on param1, param3, resultA lets expand the deps of resultA: resultB depends on param1, param3, param1 (again), param2 So to remove the shared depenency causing the synchronization problem, I would change the deps of resultB to just param3, resultA. To do that, resultA becomes an object { param1, result }. At that point the situation becomes easier to reason about:

// update resultA on a change of param1, param2
reaction(() => ({
  param1: this.param1,
  param2: this.param2
}), data => asyncCallA(data.param1, data.param2)
  .then(action(result => this.resultA = {
    param1: data.param1,
    result: result
  }))
);
// update resultB on a change of param3, resultA 
reaction(() => ({
  param3: this.param3,
  resultA: this.resultA
}), data => asyncCallB(data.param3, data.resultA)
  .then(action(result => this.resultB = result)
));

It still looks a bit nuts, but I think it's because the example is artificial and we don't know what params and results are. In reality I think you could end up with something more like:

// update resultA on a change of params
reaction(() => this.params, params => asyncCallA(params)
  .then(action(result => this.resultA = new ResultA(params, result))
));
// update resultB on a change of resultA   
reaction(() => this.resultA, resultA => asyncCallB(resultA)
  .then(action(result => this.resultB = new ResultB(resultA, result))
));

urugator avatar Sep 30 '17 17:09 urugator

@mayorovp If I modify this.param3 and this.param1 in this order inside TX, the ar2 gets sheduled first and will run before ar1 right?

urugator avatar Oct 02 '17 14:10 urugator

Maybe this will work?

const NEVER = { get() { return this; }, then() { return this; } };

var p1 = computed(() => asyncCallA(this.param1, this.param2));
var p2 = next(p1, resultA => asyncCallB(this.param1, this.param3, resultA));

this.ar1 = autorun(() => p1.get().then(resultA => this.resultA = resultA));
this.ar2 = autorun(() => p2.get().then(resultB => this.resultB = resultB));

function next(p, fn) {
    const q1 = observable.ref(NEVER);
    const q2 = computed(() =>
        mobx.extra.allowStateChanges(true, () => q1.set(NEVER));
        return p.get().then(result =>
            q1.set(computed(() => fn(result)))
        )
    );
    return computed(() => 
        q2.get();
        return q1.get().get();
    );
}

Note: this hack based on current implementation, not specification. It requires that shouldCompute should check dependencies in order of their registration.

mayorovp avatar Oct 02 '17 14:10 mayorovp

Uff, I think that this.resultB won't be updated when this.resultA is updated as a consequence of this.param2 change ...? Maybe you could replace result by this.resultA in p2? EDIT: or is that handled by q1? To me, it's not easy to think about :)

urugator avatar Oct 02 '17 15:10 urugator

@urugator in p2 result is a result of asyncCallA (see updated comment)

mayorovp avatar Oct 02 '17 16:10 mayorovp

@urugator this is handled by p.get().then(result => ...fn(result)...)

mayorovp avatar Oct 02 '17 16:10 mayorovp

Yea, nevermind, I haven't realized, that it's not neccessary to notify second autorun, because the chained fn will always run whenever asyncCallA is invoked... which explains that q1 :)

urugator avatar Oct 02 '17 16:10 urugator

or not ... I think my head is going to explode... :) -> this.param2 is changed -> ar1 is invoked -> p1.get() is called, p1 is dirty, p1 recomputes, p1 produces NEW promise -> resultA is updated -> ...how is the resultB updated...?

I don't want to question it, especially if it works, I just can't wrap my head around it.

urugator avatar Oct 02 '17 17:10 urugator

@urugator forget about ar1 - it does not matter

  1. this.param2 is changed -> p1, q2, p2 and ar2 is dirty -> p1 is computed -> q2 is computed, q1 now is NEVER, continuation for asyncCallA is registered -> p2 is computed (NEVER) -> ar2 is executed but skipped due to NEVER

  2. asyncCallA is complete -> q1 is changed by q1.set(computed(() => fn(result))) -> ar2 and p2 is dirty -> p2 is computed -> ar2 is executed, continuation for asyncCallB is registered

  3. asyncCallB is complete -> resultB changed

mayorovp avatar Oct 02 '17 18:10 mayorovp

ah ... p2 is also subscribed for this.param2 because p2.get() calls p1.get() first, make sense ... TY!

urugator avatar Oct 02 '17 19:10 urugator

Closing this issue, as it seems answered? (Too long, didn't read ;-))

mweststrate avatar Dec 04 '17 15:12 mweststrate