微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

RxJava中AndroidSchedulers.mainThread()的替代方法是什么?

RxAava中是否有与RxAndroid中的AndroidSchedulers.mainThread()同义的RxJava中的Scheduler api.
因此,如果我在新线程上安排任务,并且我想在Java主线程上观察它,我该怎么做?

编辑
下面是一个示例RxSubscription,在system.in注释时,当Observable.interval在一个单独的线程上运行时,Main线程被终止.在Android中,我可以说observeOn(AndroidSchedulers.MainThread),此后的任何操作都将在主线程上运行.我正在寻找类似的Java调度程序,因为AndroidSchedulers是RxAndroid的一部分.

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import rx.Observable;

public class Main {

public static void main(String[] args) throws InterruptedException, IOException {

    Observable<Long> values = Observable.interval(1000, TimeUnit.MILLISECONDS);
    values.subscribe(
            v -> System.out.println("Received: " + v),
            e -> System.out.println("Error: " + e),
            () -> System.out.println("Completed")
    );
    //system.in.read();
}
}

解决方法:

由于RxJava 1.x没有阻塞调度程序,因此目前无法返回“主”Java线程.

如果你可以升级到RxJava 2.x,我有一个特殊的调度程序,可以“固定”到当前线程:

compile "com.github.akarnokd:rxjava2-extensions:0.15.1"

BlockingScheduler

This type of scheduler runs its execution loop on the “current thread”, more specifically, the thread which invoked its execute() method. The method blocks until the shutdown() is invoked. This type of scheduler allows returning to the “main” thread from other threads.

public static void main(String[] args) {
    BlockingScheduler scheduler = new BlockingScheduler();

    scheduler.execute(() -> {
        Flowable.range(1, 10)
            .subscribeOn(Schedulers.io())
            .observeOn(scheduler)
            .doAfterTerminate(() -> scheduler.shutdown())
            .subscribe(v -> System.out.println(v + " on " + Thread.currentThread()));
    });

    System.out.println("BlockingScheduler finished");
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐