zoukankan      html  css  js  c++  java
  • RxJava3.0 入门教程

    一、说明

    rxjava 是基于事件的异步编程。在写代码之前,我们首先要了解几个概念。  (如果有什么错误之处,还请指正)

    • Observable(被观察者,可观察对象,就是要进行什么操作,相当于生产者)
    • bscriber 负责处理事件,他是事件的消费者
    • Operator 是对 Observable 发出的事件进行修改和变换
    • subscribeOn(): 指定 subscribe() 所发生的线程
    • observeOn(): 指定 Subscriber 所运行在的线程。或者叫做事件消费的线程

    RxJava 3具有几个基础类

    二、代码示例

    1. 一个简单代码示例

    public class Main {
    
        public static void main(String[] args) {
    
            Flowable.just("hello world ").subscribe(System.out::println);
            System.out.println("结束");
            
        }
    }
    
    // 结果:
    hello world 
    结束

    2.  结束是打印在后面

    public static void main(String[] args) {
            Flowable.range(0,5).map(x->x * x).subscribe(x->{
                Thread.sleep(1000);
                System.out.println(x);
            });
            System.out.println("结束");
        }

    3.   可设置生产者和消费者使用的线程模型 。

    public static void main(String[] args) throws Exception{
            Flowable<String> source = Flowable.fromCallable(() -> {
                Thread.sleep(1000); //  imitate expensive computation
                return "Done";
            });
    
            Flowable<String> runBackground = source.subscribeOn(Schedulers.io());
            Flowable<String> showForeground = runBackground.observeOn(Schedulers.single());
            showForeground.subscribe(System.out::println, Throwable::printStackTrace);
            System.out.println("------");
            Thread.sleep(2000);
            source.unsubscribeOn(Schedulers.io());//事件发送完毕后,及时取消发送
            System.out.println("结束");
        }

    4.   发现异步效果      是并行执行的结果

    Flowable.range(1, 10)
                    .observeOn(Schedulers.single())
                    .map(v -> v * v)
                    .subscribe(System.out::println);
            System.out.println("结束");

    5. 无异步效果

    Flowable.range(1, 10)
                    .observeOn(Schedulers.single())
                    .map(v -> v * v)
                    .blockingSubscribe(System.out::println);
            System.out.println("结束");
  • 相关阅读:
    正则表达式
    什么是面向对象
    关于jdk,jre,jvm和eclipse的一些总结
    分析ajax爬取今日头条街拍美图
    pycharm误删恢复方法及python扩展包下载地址
    django 之 视图层、模板层
    django
    django框架基础二
    jdango框架基础一
    安装软件,提高速度,可以使用清华源
  • 原文地址:https://www.cnblogs.com/chengyangyang/p/12058211.html
Copyright © 2011-2022 走看看