mobx.dart icon indicating copy to clipboard operation
mobx.dart copied to clipboard

Get the current property of an observable in another store

Open DiegoVega19 opened this issue 2 years ago • 3 comments

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'; } }

DiegoVega19 avatar Aug 18 '22 22:08 DiegoVega19

There are 2 points I would like to suggest here -

  1. Use reactions for this instead of manually calling setUsername() every time after userId changes.
  2. 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._();
}

pr-1 avatar Sep 06 '22 19:09 pr-1

Thanks, its working now! Mobx is beautiful!

DiegoVega19 avatar Sep 06 '22 21:09 DiegoVega19

You're welcome , can you please close this issue now @DiegoVega19

pr-1 avatar Sep 06 '22 22:09 pr-1