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("结束");
  • 相关阅读:
    firewalld添加/删除服务service,端口port
    centos7下配置ftp服务器
    CentOS安装vsftpd FTP后修改默认21端口方法
    虚拟机,安装tools时出现“安装程序无法继续解决
    Linux下mysql数据库备份
    测试linux下磁盘的读写速率
    redis状态详解
    office2010安装不了提示已经安装32位的了怎么办
    nginx安装部署
    结构体赋值
  • 原文地址:https://www.cnblogs.com/chengyangyang/p/12058211.html
Copyright © 2011-2022 走看看