1<Observable>.shareReplay(bufferSize) 表示可以把以前处理过的信号回放出去,不用重复处理信号
let mapO = Observable.just(10).map({ (number) -> Int in
print("MAP")
return number
}).shareReplay(1)
mapO.subscribeNext { (number) in
print(number)
}
mapO.subscribeNext { (number) in
print(number+1)
}
比如以上代码,加了shareReplay(1)之后,订阅了两次信号只会进行一次Map操作
- 使用RxMoya框架时,如果viewModel的属性里初始化直接创建了请求provider,在init方法中
class DynamicViewModel: DataSource {
var refreshDriver = PublishSubject<Void>()
var items: [DynamicModel] = [DynamicModel]()
let results: Driver<[DynamicModel]>
var dynamicProvider = RxMoyaProvider<NetWorkService>()
init(dynamicProvider: RxMoyaProvider<NetWorkService>) {
//这种情况下会出现未初始化变量而先使用该变量的错误
// results = refreshDriver.startWith(()).flatMapLatest {
// self.dynamicProvider.request(NetWorkService.User(a: .GetDynamics(user: "2390")))
// }.mapResponseToObjArray(DynamicModel).catchErrorJustReturn([]).asDriver(onErrorJustReturn: [])
//这种情况下就正常,所以建议在init方法中就要传入provider
results = refreshDriver.startWith(())
.flatMapLatest {
dynamicProvider.request(.User(a: .GetDynamics(user: "2390")))
.retry(3)
.observeOn(MainScheduler.instance)
}
.mapResponseToObjArray(DynamicModel)
.catchErrorJustReturn([])
.asDriver(onErrorJustReturn: [])
}
}