mobxjs / mobx.dart

MobX for the Dart language. Hassle-free, reactive state-management for your Dart and Flutter apps.
https://mobx.netlify.app
MIT License
2.4k stars 310 forks source link

Why some people need to avoid writes out of actions #786

Open sassanh opened 2 years ago

sassanh commented 2 years ago

I read this conversation https://github.com/mobxjs/mobx.dart/issues/206 I hope I'm not misunderstood but I think some context is missing about why it is needed for some developers to avoid directly writing on observables or why "strict-mode" was added to JavaScript version of the MobX library.

What you @pavanpodila mentioned here https://github.com/mobxjs/mobx.dart/issues/206#issuecomment-504813164 regarding performance concerns and avoiding a noisy/chatty reactive system is one of the reasons we need the "strict-mode". The other reason which has a history in immutable stores is to guarantee unidirectional data/control flow:

An event (user interaction, timely event, etc) triggers an action -> action modifies the store -> the ui will render the new store -> another event is triggered -> ...

Some software architects want to follow this pattern so that an event handler cannot directly change store and can do so only via a predefined action. It helps to keep all the logic that deals with the store in actions and others can only trigger it, so if you decide to have a setValue action to set value observable, it may initially simply be a this.value = value but in one iteration you may decide to have a different interpretation of setValue, value may become a computed/view in one iteration and you may want to keep setValue action for backward compatibility.

So it is not safe to assume x.value = v is equivalent to x.setValue(v) where setValue is purposefully there by design, and it would be nice if we were able to enforce this policy so that a junior developer or someone not familiar with the design of the codebase cannot accidentally directly write to observables.

So my question is "with the current design of MobX.dart, is it possible to have this kind of strict-mode?" (not letting developers directly write to observables) if the answer is no, can we add it as a feature? disabled by default probably, just like JavaScript library.

fzyzcjy commented 2 years ago

IMHO mobx.dart already has a flag enable/disable strict modes.

sassanh commented 2 years ago

How can I enable it? Based on this thread I thought to enable strict mode you have to use ReactiveContext which led me to https://github.com/mobxjs/mobx.dart/issues/206 which gives me the idea that you guys allow direct writes on observables even if write policy is set to ReactiveWritePolicy.always.

fzyzcjy commented 2 years ago

Interesting. Originally I thought always means any writes outside an action will throws. (I did use that flag long ago if I remember correctly)