使用RxSwift分配属性

时间:2018-04-04 05:12:32

标签: ios swift rx-swift reactivex

我们假设我们从下一页的服务器检索联系人列表:

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分配给新nextPage。我们可以在这样的背景上做到这一点:

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方法中的线程来分配属性?

1 个答案:

答案 0 :(得分:0)

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
    })