subscribeOn主线程和observerOn调用者线程RxJava2

时间:2018-03-11 14:09:51

标签: android rx-java2

我正在为非线程安全的库包装遗留代码。 当库的客户端从主线程调用API时,我需要切换到主线程,然后切换回调用者线程以返回结果

我以为我可以使用(这适用于Android,但问题更通用)

internal object TransformCompletableTemporarilySwitchToMainThread : CompletableTransformer {
    override fun apply(upstream: Completable): CompletableSource {
        return upstream
                .observeOn(Schedulers.trampoline())
                .subscribeOn(AndroidSchedulers.mainThread())
    }
}

是否有类似RxJava1的Schedulers.immediate()的内容?我知道,对于测试,您可以将Schedulers.immediate()替换为Schedulers.trampoline(),但是从文档和我运行的测试中看起来Schedulers.trampoline()与{Schedulers.immediate()没什么关系。 1}} 有替代方法吗?

ADDED

   /**
 * Returns a default, shared {@link Scheduler} instance whose {@link io.reactivex.Scheduler.Worker}
 * instances queue work and execute them in a FIFO manner on one of the participating threads.
 * <p>
 * The default implementation's {@link Scheduler#scheduleDirect(Runnable)} methods execute the tasks on the current thread
 * without any queueing and the timed overloads use blocking sleep as well.
 * <p>
 * Note that this scheduler can't be reliably used to return the execution of
 * tasks to the "main" thread. Such behavior requires a blocking-queueing scheduler currently not provided
 * by RxJava itself but may be found in external libraries.
 * <p>
 * This scheduler can't be overridden via an {@link RxJavaPlugins} method.
 * @return a {@link Scheduler} that queues work on the current thread
 */

这两部分意味着什么?

  
      
  • 返回一个默认的共享{@link Scheduler}实例,其{@link   io.reactivex.Scheduler.Worker} *实例队列工作和执行   它们以其他方式在其中一个参与线程上进行。
  •   

  
      
  • @return {@link Scheduler}队列在当前线程上工作
  •   

1 个答案:

答案 0 :(得分:2)

immediatetrampoline调度程序不适合返回特定线程。您需要一个单线程调度程序,您可以从ExecutorService

创建
ExecutorService exec = Executors.newSingleThreadedExecutor();
Scheduler singleThreaded = Schedulers.from(exec);

Observable.fromCallable(() -> api.init())
.subscribeOn(singleThreaded)
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(v -> System.out.println("Initialized"))
.observeOn(singleThreaded)
.map(v -> api.getData(v))
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(v -> System.out.println("Some data: "))
.observeOn(singleThreaded)
.doOnNext(v -> api.close())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(v -> System.out.println("Done"))
;

// later
exec.shutdown();

修改

无法返回任意线程。但是,如果一个线程有一个looper / handler,那么你可以把它变成一个带有AndroidSchedulers的调度程序,并通过observeOn来定位它。