我正在尝试将项目转换为使用 RxSwift 和 MVVM。我有一项服务,可以在每次应用启动时同步 Parse 的数据列表,我基本上想确保我采用了正确的方法。
我所做的是制作一个可变主题,然后让我的模型听这个。解析服务:
let rx_parseMushrooms = Variable<[ParseMushroom]>([])
MushroomLibraryModel:
_ = parseService.rx_parseMushrooms
.asObservable()
.map { (parseMushrooms:[ParseMushroom]) -> [Mushroom] in
let mushrooms = parseMushrooms.map { (parseMushroom:ParseMushroom) -> Mushroom in
let mushroom = Mapper<Mushroom>().map(parseMushroom.dictionaryWithValuesForKeys(parseMushroom.allKeys()))
return mushroom!
}
return mushrooms
}
.subscribeNext({ (mushrooms:[Mushroom]) -> Void in
self.mushrooms = mushrooms
print(mushrooms)
})
我也这样做来表达同步状态。
解析服务:
struct SyncState {
enum State {
case Unsynced, ConnectingToServer, SyncingInfo, FetchingImageList, SyncingImages, SyncComplete, SyncCompleteWithError
}
var infoToSync = 0
var imagesToSync = 0
var imagesSynced = 0
var state = State.Unsynced
}
let rx_syncState = Variable(SyncState())
然后我更新变量 a la
self.rx_syncState.value = self.syncState
同步视图模型:
_ = parseService.rx_syncState
.asObservable()
.subscribeNext { [weak self] (syncState:ParseService.SyncState) -> Void in
switch syncState.state {
//show stuff based on state struct
}
}
无论如何,如果有人能告诉我这是否是一种好方法,或者我是否在滥用 RxSwift(并指导我应该如何做),我将不胜感激。
干杯!