mobx icon indicating copy to clipboard operation
mobx copied to clipboard

Question: Can I rely on reaction execution order?

Open ptomask opened this issue 9 years ago • 10 comments

Greetings,

In following code:

const x = observable({
    a: 0,
    b: 0,
});

// R1
autorun(() => {
    console.log(x.a);
});

// R2
autorun(() => {
    console.log(x.a);
    x.b++;
});

// R3
autorun(() => {
    console.log(x.b);
});

x.a++;

Reaction R3 is executed as a consequence of reaction R2. My question is: Can I tell, that when I modify x.a, reaction R3 will always be triggered after both R1 and R2 reactions finished? My intuition says, that it should be so - I would expect reactions to be put into a queue and because R1 and R2 reactions are already scheduled when x.b is modified, R3 will always be put at the end of that queue. But this is not documented, so I consider that behaviour to be ... undefined.

When beginning with MobX, I was bit surprised, that reactions are not triggered in order they are defined (that would mean R1, R2 always run in that particular order, which does not hold), so I wonder whether there is at least some given order...

Thank you!

ptomask avatar Sep 04 '17 23:09 ptomask

R3 will always be triggered after both R1 and R2 reactions finished

EDIT: It turned out that autorun runs in batch, see later comments: ~~Reactions don't wait for one another. Reactions are invoked immediately when modification occurs, so they actually run from one another:~~

// R2
autorun(() => {
  console.log(x.a);
  x.b++; // the R3 is immediately synchronously invoked here
  console.log("This message is shown after R3")   // EDIT: no, its not :)
});

~~What queues the reactions are actions:~~

// R2
autorun(() => {
 console.log(x.a);
 runInAction(() => {
   x.b++; // the R3 is queued
   console.log("R3 has not yet been invoked")
   // Now all queued reactions run (at the end of outermost action) // EDIT: nope
 })    
});

EDIT: The following should be still valid I hope: The execution order is guaranteed in a sense that if you modify x.b before x.c then all reactions subscribed for x.b will run before all reactions subscribed for x.c.

However I believe that you should not use reactions as "synchronous event bus" inside a single system. Actually I think that you should treat them as being async, so you should not rely on execution order in any case.

urugator avatar Sep 05 '17 04:09 urugator

@urugator what? Reaction cannot execute inside transaction, instead stale reactions scheduled till the end of transaction.

mayorovp avatar Sep 05 '17 08:09 mayorovp

@mayorovp That's what I showed up in the second code sample or not? Autorun does not run in transaction by itself.

urugator avatar Sep 05 '17 12:09 urugator

@urugator

  1. autorun uses Reaction: autorun.ts#L48
  2. Reaction uses startBatch: reaction.ts#L109
  3. startBatch starts transaction by incrementing globalState.inBatch: observable.ts#L120

while in transaction (globalState.inBatch > 0) scheduled reactions does not executing: reaction.ts#L234

mayorovp avatar Sep 05 '17 12:09 mayorovp

@mayorovp You're right, sorry for misinforming. Should have tried it first. Edited initial comment.

urugator avatar Sep 05 '17 13:09 urugator

reactions run 'async' in relation to each other, in the sense that there is a trampoline mechanism in place. However, they run in sync, speaking from the assignment.

So

x.a++
// R1, R2 and R3 will have run here
console.log(x.a)

The order is deterministic. But not something you should rely on. Usually, modifying observables inside a reaction is an anti pattern (there are some good use cases though, so hence it is not forbidden). Like in the above example, b should have been expressed as a computed value, as it depends directly on other observables, rather then using reactions to keep them in sync.

Reactions are primarily designed to manage I/O of your application (where, by nature, the order usually doesn't matter. E.g. whether your logging reaction runs before or after your network request reaction does not matter). If your reactions are modifying data, there is usually an approach involving computed values, which are much easier to reason about then chaining reactions. (computed values will always evaluate in the right order)

mweststrate avatar Sep 05 '17 14:09 mweststrate

@urugator My example was bit bad (results in an infinite loop - wrote it at night without testing... - my original code was based on reactions without ++ unary ops. and did not do that) but its principle holds. Before I was able to write this reply, others have already wrote that - reactions are queued, run in batch and do not overtake :)

However this behaviour now exists and in some cases convenient, it is not documented, hence I considered it an implementation detail, possibly going to change in the future. That is why I asked - If I rely on it and it suddenly changes, it would break some things.

However I believe that you should not use reactions as "synchronous event bus" inside a single system.

I totally agree. As said by @mweststrate in the issue you linked (thank you for it, very helpful read!):

If you are depending on the output of a side effect, it should not be modeled as reaction but as computed value.

This is what I found too: If I (think I) need to modify a state based only on the state, there exist a function mapping between those two states and I should instead rely directly on a result of that computation and I should not perform that modification.

From now on I actually produced several pages of text containing an explanation why I wanted to use reactions just for synchronous state modification. I think nobody would read that long text (Or would you?).

I try to state the idea as simply as I am able right now:

It is generally a problem of a transformation from "what happened" - CAUSE (user clicked a button) to "what should happen" - CONSEQUENCE (an add an item, start an async request, write to local storage...). That CONSEQUENCE is for the same CAUSE different based on which state the system is in at the time the CONSEQUENCE was issued, often involved by some cross-cutting concern.

In Redux we gain a knowledge needed for state transition in an action creator then dispatch to lower-level reducers, order of which they receive the action does not matter, they all use only action payload and their own state. Nice for encapsulation.

But then the action creator tends to grow and starts to need to know too much about the whole system - becomes coupled to too many details.

And in Redux the creator also basically initiates async calls (even if I use sagas).

If I stick to this approach, for what different purpose than UI update would I need reactions?

So my approach was: Apply the action to all interrested components. Every component does only its own business - transforms its own state. Result: The order they receive the action does not matter as long as they all use only their own state and action arguments for that transition.

Then there comes a higher-level orchestration layer (containing those reactions), which says "Aha, so this component signalls this, and that component that. Which means e.g. some dropdown field value is no longer possible to choose and should be changed to some sensible default.

There can be more orchestration layers. Yes, containing other reactions.

Yes, I read more times that recursive reactive systems are unpredictable. I understand that and saw it personally. It is a pain. It creates a mess when I am not careful. It creates infinite loops or unexpected consequences, when I do not know exactly what I am doing.

But... Shall I really handle some fields onChange events in such a way it considers e.g. redirects in an imperative way? I think it is not a CONSEQUENCE of onChange. What onChange does is it transforms the form state. And only after that transition is known whether some other action takes place.

So independent order of action dispatching and state transition based on some other's component state go against each other. - Either I have to apply the action carefully in particular order to ensure that data sources are updated before data sinks (but this knowledge duplication - this dependency is already known via components holding references to other components' outputs and may change again based on the state) - or I have to wait for the system to settle in some intermediary state when I know all interrested components independently changed their states and afterwards determine what actually is the overall impact.

Hope it does make sense - Or shall I see it from a totally different perspective?

ptomask avatar Sep 06 '17 11:09 ptomask

I think we could some way conclude this thread. I have read my last post again and I see that it does not bring much value, because it is too generic and would need deeper and longer discussion with more working examples.

I went once again through all my usecases where it was not clear how to solve without having reactions just synchronously modifying state and found out, that most of them has a way of being expressed purely by minimal state and computed values. Just this solution tends to be slightly more indirect and not obvious at all at first sight, than a naive approach abusing reactions.

Main topic question of this thread has already been answered: Transactions are batched.

I just would like to ask last two questions for completness:

  1. Is this reaction batching behaviour a stable feature?
  2. @mweststrate - Can you name the "good use cases" for reactions to modify observables (my guess this will be e.g. setting a flag which tells that some async task is in progress...?)

Then imo this thread can be closed.

Thank you very much for the discussion and for developing MobX, it is saving my days. I love it!

ptomask avatar Sep 07 '17 10:09 ptomask

  1. Yes
  2. Nice use case: an observable pointing to the currently open document, and a reaction to update a most recently opened documents list.

On do 7 sep. 2017 12:27 ptomask [email protected] wrote:

I think we could some way conclude this thread. I have read my last post again and I see that it does not bring much value, because it is too generic and would need deeper and longer discussion with more working examples.

I went once again through all my usecases where it was not clear how to solve without having reactions just synchronously modifying state and found out, that most of them has a way of being expressed purely by minimal state and computed values. Just this solution tends to be slightly more indirect and not obvious at all at first sight, than a naive approach abusing reactions.

Main topic question of this thread has already been answered: Transactions are batched.

I just would like to ask last two questions for completness:

  1. Is this reaction batching behaviour a stable feature?
  2. @mweststrate https://github.com/mweststrate - Can you name the "good use cases" for reactions to modify observables (my guess this will be e.g. setting a flag which tells that some async task is in progress...?)

Then imo this thread can be closed.

Thank you very much for the discussion and for developing MobX, it is saving my days. I love it!

— You are receiving this because you were mentioned.

Reply to this email directly, view it on GitHub https://github.com/mobxjs/mobx/issues/1158#issuecomment-327759970, or mute the thread https://github.com/notifications/unsubscribe-auth/ABvGhDUIQo-oWnRTk63MwXe9Ch9ZEOcqks5sf8UfgaJpZM4PMSp3 .

mweststrate avatar Sep 07 '17 10:09 mweststrate

@mweststrate

a reaction to update a most recently opened documents list.

Isn't that the responsibility of the action that opened the document?

lillallol avatar Aug 07 '22 13:08 lillallol