Skip to content

Instantly share code, notes, and snippets.

@JEuler
Last active December 10, 2019 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JEuler/805020454f3643d47e3f816fa5a5115a to your computer and use it in GitHub Desktop.
Save JEuler/805020454f3643d47e3f816fa5a5115a to your computer and use it in GitHub Desktop.
MobX Store example
part 'some_kind_of_store.g.dart';
/// User Resources Store
class SomeKindOfStore = SomeKindOfStoreBase with _$SomeKindOfStore;
/// User Resources Store
abstract class SomeKindOfStoreBase with Store {
final WebService _webService;
final StorageService _storageService;
/// User Resources
@observable
ObservableList<DBUser> users = ObservableList.of([]);
/// Constructor
SomeKindOfStoreBase(this._webService, this._storageService);
/// Init Users from WebService
@action
Future<void> initUsers() async {
final offlineResources = await _storageService.getUsers();
if (offlineResources != null && offlineResources.length > 0) {
users = ObservableList.of(offlineResources);
}
await _webService.getUsers().then((response) {
if (response.isSuccessful) {
users = ObservableList.of(_convertAndPersistResponse(response.body.toList()));
}
});
}
_convertAndPersistResponse(List<User> list) {
final dbList = List<DBUser>.generate(list.length,
(i) => DBUser(list[i].id, list[i].avatar, list[i].name));
_storageService.saveUserResources(dbList); // Hive Storage Service (with Impl and abstract class with interface)
return dbList;
}
/// Get UserResource by id
DBUserResource getUser(int id) {
return users.firstWhere((user) => user.id == id, orElse: null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment