Autorun and observe functions of mobx response to new values

Time:2020-10-27

Autorun response function, commonly used for printing log, persisting or updating UI code

var numbers = observable([1,2,3]);var disposer = autorun(() => console.log(sum.get()));
//Output '6'
numbers.push(4);
//Output '10'

disposer();
numbers.push(5);
//No more values are output.

Observe can listen to the new and old values newvalue and oldvalue

import {observable, observe} from 'mobx';

const person = observable({
    firstName: "Maarten",
    lastName: "Luther"
});

const disposer = observe(person, (change) => {
    console.log(change.type, change.name, "from", change.oldValue, "to", change.object[change.name]);
});

person.firstName =  "Martin";
//Output: 'update firstname from Maarten to Martin'

disposer();
//Ignore any future changes

//Look at individual fields
const disposer2 = observe(person, "lastName", (change) => {
    console.log("LastName changed to ", change.newValue);
});

Address:

https://www.cnblogs.com/stumpx/p/13415830.html