为什么在 RxAndroid 中在主线程中使用 compose 运行 而在 io 线程中使用 map 运行?

Why in RxAndroid using compose running in main thread while using map running in io thread?

我有这段代码,当我使用 map 进行转换时,您可以看到 currentThread 是后台线程,而我使用 compose() 它在主线程中。 为什么它以这种方式工作,我找不到关于这个的文档。

public Single<Content> fetchContent() {
    return mEndpoint.content(id);
}


public Single<Content> fetchContent() {
    return mEndpoint.fetchContent()
            .map(content -> {
                Log.i("thread-name", "map" + Thread.currentThread());
                return content;
            })
            .compose(content -> {
                Log.i("thread-name", "compose" + Thread.currentThread());
                return content;
            });
}

//thread-name: compose. Thread[main,5,main]
//thread-name: map. Thread[OkHttp ...,10,main]


如评论中所述,compose 将立即执行 lambda,因此打印语句在主线程上 运行。

然而,compose 的参数实际上是将发出 content 的可观察对象,而不是内容本身。所以你实际上想像普通的可观察对象一样对其进行操作。例如,这是一个不会在主线程上 运行 的 map 函数:

mEndpoint.fetchContent()
        .map(content -> {
            Log.i("thread-name", "map" + Thread.currentThread());
            return content;
        })
        .compose(content -> content.map(it -> {
           Log.i("thread-name", "map" + Thread.currentThread());

           return it;
        }))

请注意,我将变量名称 content 保持不变,以便您可以轻松看出差异,但实际上应该更像这样:

.compose(obs -> obs.map(content -> {
           Log.i("thread-name", "map" + Thread.currentThread());

           return content;
        }))

最后一件事,当我有几个可以应用于可观察对象并在其他链中重用它们的操作时,我通常会使用 compose。对于简单的映射,我通常坚持 map 和朋友。