Schedulers.io() 可以用于进行异步数据库调用吗?

Can Schedulers.io() be used to make asynchronous DB calls?

可以使用 Schedulers.io() 进行异步数据库调用吗?它会阻塞我的主线程吗?

是的,它可以使用,不,它不会阻塞你的主线程。它的目的正是,异步执行阻塞IO,例如DB调用。

唯一io阻塞主线程的情况是池中的所有线程都被占用;默认调度程序不应该发生这种情况,但是如果您想控制最多启动多少个线程,您可以设置 custom Scheduler 的大小有限为了避免你的 ram 中的线程聚会:

Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(3));

判断哪种方法最适合您。第一个使事情变得更简单,并且永远不会阻塞主线程。相反是来自默认调度程序的克隆的攻击。第二种,如果配置好,是最佳选择。

以及一些使用方法:

Observable.just("yourDbTable")
         .flatMap(t->{ Record rec = selectFrom(t); .... })
         .subscribeOn(Schedulers.io()); 

Schedulers.io()

Creates and returns a Scheduler intended for IO-bound work. The implementation is backed by an Executor thread-pool that will grow as needed. This can be used for asynchronously performing blocking IO.

The implementation is backed by a pool of single-threaded ScheduledExecutorService instances that will try to reuse previously started instances used by the worker returned by Scheduler.createWorker() but otherwise will start a new backing ScheduledExecutorService instance.

Note that this scheduler may create an unbounded number of worker threads that can result in system slowdowns or OutOfMemoryError. Therefore, for casual uses or when implementing an operator, the Worker instances must be disposed via Disposable.dispose().

文档还建议避免对其进行计算工作