关于RxJava2的一点总结

我是基于以下依赖做的总结,之前由于依赖的版本太低导致有些包缺失,推荐就用最新的吧

    implementation 'io.reactivex.rxjava2:rxjava:2.1.12'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
冷流的基础用法(不含操作符)

冷流:只有在订阅的时候才会发射数据

//普通用法
  Observable.create {
            it.onNext(0)
            it.onComplete()
        }.subscribe({
                    //onNext
        },{
            //onError
        },{
            //onComplete
        })

//数据特别多的时候,做背压,场景:IM聊天消息
        Flowable.create({
            it.onNext(1)
            it.onComplete()
        }, BackpressureStrategy.BUFFER)
            .subscribe({
                //onNext
            },{
                //onError
            },{
                //onComplete
            })

//以下两种可搭配网络请求来使用,视情况而定
        Maybe.create {
            it.onSuccess(2)
            it.onComplete()
        }.subscribe({ 
             //onSuccess
            //可为null  -->Maybe
        },{
            //onError
        })

        Single.create {
            //只发射一次 --> Single  无 onComplete
            it.onSuccess(3)
//            it.onError(IOException(""))

        }.subscribe { t1, t2 ->
            //t1:onSuccess的值  t2:Exception
        }


  //以下两种可做检查登录 应该是一致的,第二种可做线程切换,第一种判断是否切换那里做不了线程切换
        if (true){
            Completable.complete()
        }else{
            Completable.error(IllegalStateException("没登录"))
        }.subscribe({
            //直接执行目标行为
        },{
            //异常,去登录
        })


        Completable.create {
            val login = false
            if (login){
                it.onComplete()
            }else{
                it.onError(IllegalStateException("没登录"))
            }
        }.subscribe({
                    //直接执行目标行为
        },{
            //异常,去登录
        })


热流基础用法(不含操作符)

这个用的比较多,场景:MVVM里作为ViewModel和View之间通信,类似于LiveData

// observer will receive all 4 events (including "default").
BehaviorSubject subject = BehaviorSubject.createDefault("default");
subject.subscribe(observer);
subject.onNext("one");
subject.onNext("two");
subject.onNext("three");

// observer will receive the "one", "two" and "three" events, but not "zero"
BehaviorSubject subject = BehaviorSubject.create();
subject.onNext("zero");
subject.onNext("one");
subject.subscribe(observer);
subject.onNext("two");
subject.onNext("three");

// observer will receive only onComplete
BehaviorSubject subject = BehaviorSubject.create();
subject.onNext("zero");
subject.onNext("one");
subject.onComplete();
subject.subscribe(observer);

// observer will receive only onError
BehaviorSubject subject = BehaviorSubject.create();
subject.onNext("zero");
subject.onNext("one");
subject.onError(new RuntimeException("error"));
subject.subscribe(observer); 
 

                            
                        
                    
                    
                    

你可能感兴趣的:(关于RxJava2的一点总结)