使用Rxjava Schedulers.newThread()与Schedulers.io()进行改造 [英] Retrofit with Rxjava Schedulers.newThread() vs Schedulers.io()

查看:110
本文介绍了使用Rxjava Schedulers.newThread()与Schedulers.io()进行改造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Retrofit 网络请求中使用 Schedulers.newThread() Schedulers.io()相比有什么好处.我已经看到许多使用 io()的示例,但是我想了解原因.

What are the benefits to use Schedulers.newThread() vs Schedulers.io() in Retrofit network request. I have seen many examples that use io(), but I want to understand why.

示例情况:

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

vs

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

我看到的原因之一是-

newThread()为每个工作单元创建一个新线程. io()将使用线程池

newThread() creates a new thread for each unit of work. io() will use a thread pool

但是该参数对应用程序有什么影响?还有什么其他方面?

But what is the influence of that argument on the app? And what other aspects there are?

推荐答案

您正确地认为,使用 Schedulers.io()的好处在于它使用了线程池,而 Schedulers.newThread()没有.

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:

这篇关于使用Rxjava Schedulers.newThread()与Schedulers.io()进行改造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆