• 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("结束");
  • 相关阅读:
    Codeforces 712B. Memory and Trident
    Codeforces 712A. Memory and Crow
    kkb --- webpack实战
    前端性能优化
    前端防抖
    css面试题
    七、服务端渲染 ---kkb
    数据结构与算法(位运算)
    数据结构与算法(栈、队列、链表)
    vue-cli 配置项以及请求的封装
  • 原文地址:https://www.cnblogs.com/chengyangyang/p/12058211.html
Copyright © 2020-2023  润新知