使用 Rxjava Schedulers.newThread()与 Schedulers.io()进行改进

Retrofit网络请求中使用 Schedulers.newThread()Schedulers.io()的好处是什么。我见过许多使用 io()的例子,但是我想知道为什么。

例子:

observable.onErrorResumeNext(refreshTokenAndRetry(observable))
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())...

observable.onErrorResumeNext(refreshTokenAndRetry(observable))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())...

我看到的原因之一是

newThread()为每个工作单元创建一个新线程

但是这个争论对应用程序有什么影响? 还有其他什么方面呢?

16066 次浏览

You are correct that the benefit of using Schedulers.io() lies in the fact that it uses a thread pool, whereas Schedulers.newThread() does not.

The primary reason that you should consider using thread pools is that they maintain a number of pre-created threads that are idle and waiting for work. This means that when you have work to be done, you don't need to go through the overhead of creating a thread. Once your work is done, that thread can also be re-used for future work instead of constantly creating and destroying threads.

Threads can be expensive to create, so minimizing the number of threads that you are creating on the fly is generally good.

For more information on thread pools, I recommend: