rxjava多线程切换

本文通过四个示例展示了RxJava中不同线程调度器的使用方式,包括操作符和订阅者运行在不同线程上的情况。这些示例帮助理解Observable、操作符及订阅者如何在不同线程间交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args) {
    Observable.fromCallable(thatReturnsNumberOne())     // the Observable
            .map(numberToString())                      // the Operator
            .subscribe(printResult());                  // the Subscriber
}

/*
    Output of the above program:
    ---------------------------
    Observable thread: main
    Operator thread: main
    Subscriber thread: main
    Result: 1
*/

        
private Callable<Integer> thatReturnsNumberOne() {
    return () -> {
        System.out.println("Observable thread: " + Thread.currentThread().getName());
        return 1;
    };
}

private Func1<Integer, String> numberToString() {
    return number -> {
        System.out.println("Operator thread: " + Thread.currentThread().getName());
        return String.valueOf(number);
    };
}

private Action1<String> printResult() {
    return result -> {
        System.out.println("Subscriber thread: " + Thread.currentThread().getName());
        System.out.println("Result: " + result);
    };
}




public static void main(String[] args) {
    Observable.fromCallable(thatReturnsNumberOne())
            .map(numberToString())
            .observeOn(Schedulers.newThread())      // subscriber on different thread
            .subscribe(printResult());
}
/*
    Output of the above program:
    ---------------------------
    Observable thread: main
    Operator thread: main
    Subscriber thread: RxNewThreadScheduler-1
    Result: 1
*/

public static void main(String[] args) {
    Observable.fromCallable(thatReturnsNumberOne())
            .observeOn(Schedulers.newThread())      // operator on different thread
            .map(numberToString())
            .subscribe(printResult());
}
/*
    Output of the above program:
    ---------------------------
    Observable thread: main
    Operator thread: RxNewThreadScheduler-1
    Subscriber thread: RxNewThreadScheduler-1
    Result: 1
*/

public static void main(String[] args) {
    Observable.fromCallable(thatReturnsNumberOne())
            .observeOn(Schedulers.newThread())      // operator on different thread
            .map(numberToString())
            .observeOn(Schedulers.newThread())      // subscriber on different thread
            .subscribe(printResult());
}
/*
    Output of the above program:
    ---------------------------
    Observable thread: main
    Operator thread: RxNewThreadScheduler-2
    Subscriber thread: RxNewThreadScheduler-1
    Result: 1
*/


原文:https://praveer09.github.io/technology/2016/02/29/rxjava-part-3-multithreading/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值