【问题标题】:Rxjava2 blockingSubscribe vs subscribeRxjava2 阻塞订阅与订阅
【发布时间】:2019-01-10 11:50:38
【问题描述】:

我已经阅读了关于blockingSubscribe()subscribe() 的解释,但我既不能写也不能找到例子来看看它们的区别。似乎这两者的工作方式相同。有人可以提供这两个的例子,最好是Java。

【问题讨论】:

    标签: java kotlin rx-java2


    【解决方案1】:

    blockingSubscribe 阻塞当前线程并在那里处理 incomnig 事件。您可以通过运行一些异步源来看到这一点:

    System.out.println("Before blockingSubscribe");
    System.out.println("Before Thread: " + Thread.currentThread());
    
    Observable.interval(1, TimeUnit.SECONDS)
    .take(5)
    .blockingSubscribe(t -> {
         System.out.println("Thread: " + Thread.currentThread());
         System.out.println("Value:  " + t);
    });
    
    System.out.println("After blockingSubscribe");
    System.out.println("After Thread: " + Thread.currentThread());
    

    subscribe 没有这样的限制,可以在任意线程上运行:

    System.out.println("Before subscribe");
    System.out.println("Before Thread: " + Thread.currentThread());
    
    Observable.timer(1, TimeUnit.SECONDS, Schedulers.io())
    .concatWith(Observable.timer(1, TimeUnit.SECONDS, Schedulers.single()))
    .subscribe(t -> {
         System.out.println("Thread: " + Thread.currentThread());
         System.out.println("Value:  " + t);
    });
    
    
    System.out.println("After subscribe");
    System.out.println("After Thread: " + Thread.currentThread());
    
    // RxJava uses daemon threads, without this, the app would quit immediately
    Thread.sleep(3000);
    
    System.out.println("Done");
    

    【讨论】:

    • 那么,它在当前函数 (main()) 正在运行的主 Thread 中运行 Observer 的操作?
    • @LiTTle,是的,我刚刚检查过。
    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 2023-03-23
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多