I want a clear method for creating stores that I can refresh when I know new service data is available (like lazyObservable
from mobx-utils
), but easily attach more computed values and action functions.
Starting from create-react-app, use this index.js
.
import React from 'react';
import ReactDOM from 'react-dom';
import {observable} from 'mobx';
import {observer} from 'mobx-react';
import {asyncAction} from 'mobx-utils';
const flipACoin = () => Math.random() > 0.5;
function determineGodliness() {
const screwYourRAM = new Array(1000000).fill(Math.random());
return new Promise((resolve) => {
setTimeout(() => {
resolve([flipACoin(), flipACoin()]);
}, 1500);
});
}
function godStore() {
const store = observable({
alpha: false,
omega: false,
waiting: false,
refresh: asyncAction(function *() {
this.waiting = true;
[this.alpha, this.omega] = yield determineGodliness();
this.waiting = false;
}),
get isGod() {
return this.alpha && this.omega;
}
});
store.refresh();
return store;
}
window.store = godStore();
const App = observer(({store}) => <p>{
(store.waiting)
? 'The suspense is killing me!'
: (store.isGod)
? 'I am the Alpha and the Omega'
: 'I just work here.'
}</p>);
ReactDOM.render(<App store={window.store} />, document.getElementById('root'));
Task manager shows memory usage increase every time you run window.store.refresh()
in the console. Interestingly enough, using setInterval(window.store.refresh, 3000)
actually causes oscillation in memory usage instead of a linear climb. Between those two conflicting cases I am confused as to how the garbage collector views this setup.
What can I do to be absolutely sure that screwYourRAM
will eventually get garbage collected? All I care about keeping is what's returned from the generator, not what was allocated in the interim.