Ios 使用RxSwift分配属性
假设我们使用下一页从服务器检索联系人列表:Ios 使用RxSwift分配属性,ios,swift,rx-swift,reactivex,Ios,Swift,Rx Swift,Reactivex,假设我们使用下一页从服务器检索联系人列表: retrieveContacts() .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] contacts, nextPage in self?.nextPage = nextPage
retrieveContacts()
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] contacts, nextPage in
self?.nextPage = nextPage
// do something with contacts
})
.disposed(by: disposeBag)
现在我们想将这些联系人传递给其他观察对象,但同时我们必须将self.nextPage
分配给newnextPage
。我们可以在这样的背景下进行:
retrieveContacts()
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.observeOn(MainScheduler.instance)
.map { [weak self] contacts, nextPage in
self?.nextPage = nextPage
return Observable.just(contacts)
}
.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.map { contacts in
// do something with contacts but now on background
}
是否有更好的方法通过更改.observeOn
方法中的线程来分配属性
let observable = retrieveContacts()
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.share()
observable.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] contacts, nextPage in
self?.nextPage = nextPage
// do something with nextPage
})
observable.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.subscribe(onNext: { [weak self] contacts, nextPage in
self?.contacts = contacts
// do something with contacts
})