【问题标题】:Does the order of subscribeOn and observeOn matter?subscribeOn 和 observeOn 的顺序重要吗?
【发布时间】:2016-10-24 17:09:37
【问题描述】:

我对在 observables 上调用 subscribeOnobserveOn 方法的顺序有点困惑。我读了几篇文章,一个人说没关系,只是在他的例子中使用了东西,而其他人说这很重要。所以这是我的问题:

例如:

self.remoteService.rxGetAllLanguages()
            .observeOn(MainScheduler.instance)
            .subscribeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
            .subscribe({ e in
                switch e {
                case .Next(let element):

                case .Error(let e):
                    DDLogError("Error in  \(e)")
                case .Completed:
                    DDLogDebug("Completed")
                }
                }
            ).addDisposableTo(self.disposeBag)

是否和以下一样:

  self.remoteService.rxGetAllLanguages()
                    .subscribeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
                    .observeOn(MainScheduler.instance)
                    .subscribe({ e in
                        switch e {
                        case .Next(let element):

                        case .Error(let e):
                            DDLogError("Error in  \(e)")
                        case .Completed:
                            DDLogDebug("Completed")
                        }
                        }
                    ).addDisposableTo(self.disposeBag)

如果我正确理解它们的机制,它们是不同的。第一个在主线程上完成所有工作,第二个在另一个线程上完成所有工作,然后分派回主线程。但我很确定,所以有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: swift multithreading rx-swift


    【解决方案1】:

    在链中调用subscribeOn() 的位置并不重要。你打电话给observeOn() 的地方很重要。

    subscribeOn() 告诉整个链开始 处理哪个线程。每个链只应该调用一次。如果您在流的下游再次调用它,它将无效。

    observeOn() 导致在它下面发生的所有操作都在指定的调度程序上执行。您可以在每个流中多次调用它以在不同线程之间移动。

    举个例子:

    doSomethingRx()
        .subscribeOn(BackgroundScheduler)
        .doAnotherThing()
        .observeOn(ComputationScheduler)
        .doSomethingElse()
        .observeOn(MainScheduler)
        .subscribe(//...)
    
    • subscribeOn 导致在 BackgroundScheduler 上调用 doSomethingRx
    • doAnotherThing 将继续使用 BackgroundScheduler
    • 然后observeOn 将流切换到 ComputationScheduler
    • doSomethingElse 将在 ComputationScheduler 上发生
    • 另一个observeOn 将流切换到 MainScheduler
    • 订阅发生在 MainScheduler 上

    【讨论】:

    • 嗨 @Jahnold,RxSwift 文档说 - “如果你想开始序列生成(订阅方法)并在特定调度程序上调用 dispose,请使用 subscribeOn(scheduler)。”这是否意味着,如果我们指定 subscribeOn(:),它将在指定线程上启动链,并且一次性的 dispose 将在同一指定线程上调用?
    【解决方案2】:

    .subscribeOn() 运算符影响将创建哪个调度程序链(在它的左侧)并且它工作一次。 .observeOn() 影响其右侧的运算符 - 调度程序数据将在运算符之后处理。

    【讨论】:

      【解决方案3】:

      是的,你是对的。 observeOn 只会接收您指定线程上的事件,而subscribeOn 将实际执行指定线程中的工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-12
        • 1970-01-01
        • 2019-10-11
        • 1970-01-01
        • 1970-01-01
        • 2016-06-10
        • 2018-06-28
        • 1970-01-01
        相关资源
        最近更新 更多