OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 RxSwift 分配属性 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:58
标题: ios - 使用 RxSwift 分配属性

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

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



Best Answer-推荐答案


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

关于ios - 使用 RxSwift 分配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49643251/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4