我是 RxSwift 和 RX 的整个概念的新手,我想知道如何处理 RxSwift 从远程服务器获取的全局应用程序状态。
假设我需要获取 JSON 并将其解析为对象列表以在 TableView 中显示它,而且我还需要创建格式为 [{id: object}, ...]
的 map 在应用程序的其他部分使用数据。
例如:应用程序重复从服务器获取人员列表,并且需要人员 TableView 的数据以及人员消息以显示头像和状态以及相关消息。因此, View 模型 PersonViewModel
和由模型 Person 和 Message 组成的 MessageViewModel
需要数据。
将是拥有这种结构的正确方法:
struct Person {
let id: personId
let fullName: String
let status: personStatus
}
class PeopleStore {
var order: [personId] = []
var dataMap: [personId: Person] = [:]
init(people: [Person]) {
order = people.map { $0.id }
for person in people {
dataMap[person.id] = person
}
}
}
class AppState {
let rx_peopleStore: Variable<PeopleStore>
init(peopleStore: PeopleStore) {
self.rx_peopleStore = Variable(peopleStore)
}
}
并通过从服务器获取来调整应用状态:
...
_ = PeopleApi
.rx_peopleStore
.asDriver(onErrorJustReturn: [])
.driveNext { peopleStore in
sharedAppState.rx_peopleStore.value = peopleStore
}
...
在 View 模型中:
...
_ = sharedAppState
.rx_peopleStore
.asDriver()
.driveNext { store in
// refreshUI by data from store
}
.addDisposableTo(bag)
...
这是正确的方法还是存在一些不同的更好的方法?我还想(将来)获取的数据保留下来。最佳做法是什么?谢谢。
附言抱歉代码中有拼写错误,如果有的话。没编译就直接写了。
最佳答案
我在保持不同事物的最近状态(如服务器响应、地理位置等)方面遇到了类似的问题,并最终为此制作了一个轻量级的基于 Rx 的框架,从那以后我一直在使用它,看看它是否适合你也需要 - https://github.com/maxvol/RaspSwift
关于swift - 如何使用 RxSwift 处理应用程序状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36691483/