Last active
December 10, 2019 07:53
-
-
Save JEuler/805020454f3643d47e3f816fa5a5115a to your computer and use it in GitHub Desktop.
MobX Store example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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