菜鸟教程小白 发表于 2022-12-11 19:58:43

ios - 使用 RxSwift 分配属性


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

<pre><code>retrieveContacts()
    .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
    .observeOn(MainScheduler.instance)
    .subscribe(onNext: { contacts, nextPage in
      self?.nextPage = nextPage
      // do something with contacts
    })
    .disposed(by: disposeBag)
</code></pre>

<p>现在我们想将这些联系人传递给其他可观察对象,但同时我们必须将 <code>self.nextPage</code> 分配给新的 <code>nextPage</code>。我们可以在后台这样做:</p>

<pre><code>retrieveContacts()
      .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
      .observeOn(MainScheduler.instance)
      .map { 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
      }
</code></pre>

<p>有没有更好的方法通过更改<code>.observeOn</code>方法中的线程来分配属性?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><pre><code>let observable = retrieveContacts()
    .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
    .share()

    observable.observeOn(MainScheduler.instance)
    .subscribe(onNext: { contacts, nextPage in
      self?.nextPage = nextPage
      // do something with nextPage
    })

    observable.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
    .subscribe(onNext: { contacts, nextPage in
      self?.contacts = contacts
      // do something with contacts
    })
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 使用 RxSwift 分配属性,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/49643251/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/49643251/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 使用 RxSwift 分配属性