我需要在与subscribeOn
相同的主题中运行Observable
操作。我找到了一个解决方案,但似乎并不是最好的。基本上我使用相同的scheduler
用于初始observable
和observable
doOnSubscribe
返回:
Scheduler singleThreadScheduler = Schedulers.from(Executors.newSingleThreadExecutor());
Observable<Object> obs = Observable.create(subscriber -> {
System.out.println("onNext at: " + Thread.currentThread());
subscriber.onNext(new Object());
subscriber.onCompleted();
}).subscribeOn(singleThreadScheduler).observeOn(Schedulers.newThread());
obs = obs.doOnSubscribe(() -> System.out.println("doOnSubscribe at: " + Thread.currentThread())).subscribeOn(singleThreadScheduler);
obs.subscribe(o -> {
System.out.println("result at: " + Thread.currentThread());
});
日志:
doOnSubscribe at: Thread[pool-1-thread-1] //runs on the same thread
onNext at: Thread[pool-1-thread-1] //runs on the same thread
result at: Thread[RxNewThreadScheduler-1]
有没有更好或更标准的方法来实现它?
答案 0 :(得分:-1)
正如akarnokd所说,我在问题中提到的解决方案只有一个。