问题描述
考虑以下场景:
- 比方说,我们想用 mobx 编写一个书店应用
- 我在我的书域商店中有一个 ObservableMap 来保存书籍的 id 键
- 我经常通过 api 请求获取书籍更新,这些返回代表书籍的 json 对象
- 为了保持引用的完整性,mobx 推荐 updating existing instances
- 给定 json 很容易创建一本新书,但我如何将此数据合并到现有实例中(在现有地图中引用)?
明显的解决方案是自己编写合并函数,但这不是可扩展的,实际应用程序通常有一堆不同的模型。你能给我指出任何好的序列化框架,它们提供这样的合并功能(除了工厂构造函数和导出)还是我误解了一个重要的 mobx 概念?
场景的示例代码:
book_model.dart
class Book = _Book with _$Book;
abstract class _Book with Store {
final String id;
@observable
String title;
_Book({
required this.id,required this.title,});
}
book_store.dart
class BookStore = _BookStore with _$BookStore;
abstract class _BookStore with Store {
final BookService bookService;
@observable
final ObservableMap<String,Book> books;
fetchPatients() async{
final apiRes = await bookService.fetchBooks();
// somehow merge the apiRes in the existing books map
// DONT wanna do smth like this,as this would
// break existing references
books = Map.fromIterable(
apiRes.map((res)=>Book.fromJson(res)),key: (b) => b.id,calue: (b) => b,);
// instead im looking for smth like this
// which looks up matching keys and copies
// values from the new book data to the
// old one,and also adds / deletes
// new / removed keys from the old map
joinDeep(books,Map.fromIterable(
apiRes.map((res)=>Book.fromJson(res)),));
}
}
book_service.dart
class PatientService {
static final exampleData = [];
fetchBooks() async{
//do something to fetch the books from the api
final apiRes = await http.get(/*some url*/);
return apiRes;
}
}
解决方法
试试这个
books
..removeWhere((key,value) => !newBooks.containsKey(key))
..addAll(newBooks);