Mobx: autorun with an async/await function as an argument

Created on 17 May 2017  路  6Comments  路  Source: mobxjs/mobx

Hi everyone!

I have a question about passing an async/await function as an argument to autorun.
I'm using react-native, and I want to call AsyncStorage whenever this.credentials.username changes. So for that reason I used autorun.
I also wanted to use async/await functions, but here's the problem :D
This one works perfectly, autorun calls the function whenever I change this.credentials.username
screen shot 2017-05-18 at 12 25 28 am
However, in this example autorun calls the argument function only ONCE and after that it doesn't response on any changes made in this.credentials.username
screen shot 2017-05-18 at 12 24 56 am

So the question is:
Is this a bug? Or is mobx constructed this way so I will never be able to use async/await functions with autorun? :)
Well, if this is a bug, I can try to find that bug and make a PR :)
versions:
node v7.10.0
mobx v3.1.9
react-native v0.42.0

Most helpful comment

@urugator thank you very much! I've also come up with some workaround which lets me use async/await function. This is for somebody who is still interested how to make it work :D
screen shot 2017-05-18 at 11 38 50 am

All 6 comments

Your second example can be "transpiled" like this:

const disposer = autorun(() => {  
  // Autorun subscribes for any observable accessed during the execution of this function
  return Promise.resolve()
    .then(() => {
      // This function is deffered, it won't be executed until the function passed to autorun finishes      
      // Therefore the username is not accessed during the execution of the function passed to autorun
      // Therefore the MobX won't subscribe for anything dereferenced inside this function
      return AsynStorage.getItem(this.credentials.username);      
    })
    .then(res => {
      console.log(JSON.parse(res));
    });      
});

So not a bug, the observables must be accessed synchronously - during the execution of autorun.

@urugator good example, made it explicit to me. Thank you

@urugator thank you very much! I've also come up with some workaround which lets me use async/await function. This is for somebody who is still interested how to make it work :D
screen shot 2017-05-18 at 11 38 50 am

And yeah, closing the issue :)

any update on this use case. ?

It's closed so there is nothing to update about, read the rationale and open a fresh issue if you need anything more.

Was this page helpful?
0 / 5 - 0 ratings