mobx.dart
mobx.dart copied to clipboard
Get the current property of an observable in another store
Hello. I need help is it possible to get the current property of an observable in another store? for example I'm using Provider
class UserStore = _UserStore with _$UserStore;
abstract class _UserStore with Store { @observable int userID = 0; //This action load when the screen init @action initUserId(){ userId = 24; } }
class RequestStore = _RequestStore with _$RequestStore;
abstract class _RequestStore with Store { final userStore = UserStore(); @observable String greeting = 0; //This action after userID is updated @action setUsername(){ int id = userStore.userID //Returns 0 the initial state but i need the get 24 greeting = 'hello $id'; } }
There are 2 points I would like to suggest here -
- Use reactions for this instead of manually calling setUsername() every time after userId changes.
- When you do
final userStore = UserStore()
a new object of UserStore is created and you are changing the userId of another object.
This can be explained by following example -
final userStore1 = UserStore();
final userStore2 = UserStore();
userStore1.initUserId();
print(userStore1.userId);// prints 24
print(userStore2.userId); // prints 1
For solving this you need to make UserStore a Singleton. This means you have to use a single object of your UserStore everywhere. Like this -
class UserStore extends _UserStore with _$UserStore {
UserStore._();
factory UserStore.getInstance() => _instance;
static final UserStore _instance = UserStore._();
}
Thanks, its working now! Mobx is beautiful!
You're welcome , can you please close this issue now @DiegoVega19