Android RxJava 3.x 使用总结

转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/106720158
本文出自【赵彦军的博客】

文章目录

    • 依赖接入
    • Flowable
    • Single
    • Maybe
    • BackpressureStrategy
    • 线程切换
    • concat
      • 例子1

依赖接入

implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
implementation "io.reactivex.rxjava3:rxjava:3.0.4"

Flowable

//java 方式
Flowable.just(1)
        .subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Throwable {

            }
          }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Throwable {

            }
        });

//或者用 Lambda 简写
Flowable.just(1)
         .subscribe( it -> {

         }, throwable -> {

         });

range 一组序列数据

Flowable.range(0, 4)
        .subscribe(it -> {

            //结果 0 1 2 3

        }, throwable -> {

        });

Single

Single只发射单个数据或错误事件,即使发射多个数据,后面发射的数据也不会处理。
只有 onSuccessonError事件,没有 onNextonComplete事件。

SingleEmitter

public interface SingleEmitter<@NonNull T> {

    void onSuccess(@NonNull T t);
    void onError(@NonNull Throwable t);
    void setDisposable(@Nullable Disposable d);
    void setCancellable(@Nullable Cancellable c);
    boolean isDisposed();
    boolean tryOnError(@NonNull Throwable t);
    
}

示例1

   Single.create(new SingleOnSubscribe<Integer>() {

            @Override
            public void subscribe(@NonNull SingleEmitter<Integer> emitter) throws Throwable {
                emitter.onSuccess(1);
               }
             })
                .subscribe(integer -> {

                }, throwable -> {

                });

示例2

  Single.just(1)
        .subscribe(integer -> {

         }, throwable -> {

         });

Maybe

Maybe 是 RxJava2.x 之后才有的新类型,可以看成是Single和Completable的结合。
Maybe 也只能发射单个事件或错误事件,即使发射多个数据,后面发射的数据也不会处理。
只有 onSuccessonErroronComplete事件,没有 onNext 事件。

public interface MaybeEmitter<@NonNull T> {

    void onSuccess(@NonNull T t);
    void onError(@NonNull Throwable t);
    void onComplete();
    void setDisposable(@Nullable Disposable d);
    void setCancellable(@Nullable Cancellable c);
    boolean isDisposed();
    boolean tryOnError(@NonNull Throwable t);
    
}

实例1

Maybe.create(new MaybeOnSubscribe<Integer>() {
            @Override
            public void subscribe(@NonNull MaybeEmitter<Integer> emitter) throws Throwable {
                emitter.onSuccess(1);
                emitter.onComplete();
                }
              })
                .subscribe(integer -> {

                }, throwable -> {

                });

实例2

   Maybe.just(1)
        .subscribe(integer -> {
                    
         }, throwable -> {

        });

BackpressureStrategy

背压策略

public enum BackpressureStrategy {
    /**
     * The {@code onNext} events are written without any buffering or dropping.
     * Downstream has to deal with any overflow.
     * 

Useful when one applies one of the custom-parameter onBackpressureXXX operators. */ MISSING, /** * Signals a {@link io.reactivex.rxjava3.exceptions.MissingBackpressureException MissingBackpressureException} * in case the downstream can't keep up. */ ERROR, /** * Buffers all {@code onNext} values until the downstream consumes it. */ BUFFER, /** * Drops the most recent {@code onNext} value if the downstream can't keep up. */ DROP, /** * Keeps only the latest {@code onNext} value, overwriting any previous value if the * downstream can't keep up. */ LATEST }

  • MISSING 策略则表示通过 Create 方法创建的 Flowable 没有指定背压策略,不会对通过 OnNext 发射的数据做缓存或丢弃处理,需要下游通过背压操作符
  • BUFFER 策略则在还有数据未下发完成时就算上游调用onComplete或onError也会等待数据下发完成
  • LATEST 策略则当产生背压时仅会缓存最新的数据
  • DROP 策略为背压时丢弃背压数据
  • ERROR 策略是背压时抛出异常调用onError
 Flowable.create(new FlowableOnSubscribe<Long>() {

            @Override
            public void subscribe(@NonNull FlowableEmitter<Long> emitter) throws Throwable {

                emitter.onNext(1L);
                emitter.onNext(2L);
                emitter.onComplete();

            }

        }, BackpressureStrategy.DROP)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(it -> {

                }, throwable -> {

                });

线程切换

RxUtil

package com.example.stream

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.FlowableTransformer
import io.reactivex.rxjava3.core.MaybeTransformer
import io.reactivex.rxjava3.core.ObservableTransformer
import io.reactivex.rxjava3.core.SingleTransformer
import io.reactivex.rxjava3.schedulers.Schedulers

/**
 * @author yanjun.zhao
 * @time 2020/6/12 8:39 PM
 * @desc
 */

object RxUtil {

    /**
     * 线程切换
     */
    fun <T> maybeToMain(): MaybeTransformer<T, T> {

        return MaybeTransformer { upstream ->
            upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    /**
     * 线程切换
     */
    fun <T> singleToMain(): SingleTransformer<T, T> {

        return SingleTransformer { upstream ->
            upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    /**
     * 线程切换
     */
    fun <T> flowableToMain(): FlowableTransformer<T, T> {

        return FlowableTransformer { upstream ->
            upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

    fun <T> observableToMain(): ObservableTransformer<T, T> {

        return ObservableTransformer { upstream ->
            upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }
    }

}

具体实现

package com.example.stream

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Single

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Single.just(1)
            .map {
                //运行在子线程
                it
            }
            .compose(RxUtil.singleToMain())  //线程转换
            .subscribe(
                {
                    //运行在主线程
                },
                {
                    it.printStackTrace()
                }
            )

        Maybe.just(1)
            .map {
                //运行在子线程
                it
            }
            .compose(RxUtil.maybeToMain())  //线程转换
            .subscribe(
                {
                    //运行在主线程
                },
                {
                    it.printStackTrace()
                }
            )


        Flowable.just(1)
            .map {
                //运行在子线程
                it
            }
            .compose(RxUtil.flowableToMain())  //线程转换
            .subscribe(
                {
                    //运行在主线程
                },
                {
                    it.printStackTrace()

                }
            )

        Observable.just(1)
            .map {
                //运行在子线程
                it
            }
            .compose(RxUtil.observableToMain())  //线程转换
            .subscribe(
                { it ->
                    //运行在主线程
                },
                {
                    it.printStackTrace()
                }
            )

    }
}

concat

Android RxJava 3.x 使用总结_第1张图片

Concat操作符连接多个Observable的输出,就好像它们是一个Observable,第一个Observable发射的所有数据在第二个Observable发射的任何数据前面,以此类推。

直到前面一个Observable终止,Concat才会订阅额外的一个Observable。注意:因此,如果你尝试连接一个"热"Observable(这种Observable在创建后立即开始发射数据,即使没有订阅者),Concat将不会看到也不会发射它之前发射的任何数据。

例子1

  private var ob1 = Observable.create<String> {
        Log.d("concat-数据源1", " ${Thread.currentThread().name} ")
        it.onNext("a1")
        it.onComplete()
    }

    private var ob2 = Observable.create<String> {
        Log.d("concat-数据源2", " ${Thread.currentThread().name} ")
        it.onNext("a2")
        it.onComplete()
    }
    private var ob3 = Observable.create<String> {
        Log.d("concat-数据源3", " ${Thread.currentThread().name} ")
        it.onNext("a3")
        it.onComplete()
    }

  Observable.concat<String>(ob1, ob2, ob3)
            .subscribeOn(Schedulers.io())
            .subscribe{
                Log.d("concat-结果", " ${Thread.currentThread().name} " + it)
            }

结果是:

concat-数据源1:  RxCachedThreadScheduler-1 
concat-结果:  RxCachedThreadScheduler-1 
concat-数据源2:  RxCachedThreadScheduler-1 
concat-结果:  RxCachedThreadScheduler-1 
concat-数据源3:  RxCachedThreadScheduler-1 
concat-结果:  RxCachedThreadScheduler-1 

结果分析:

  • concat 输出结果是有序的
  • concat 会使三个数据源都会执行

那么如果我要实现哪个数据源有数据,我就用哪个数据,一旦获取到想要的数据,后续数据源不再执行。其实很简单,用 firstElement() ,这个需求有点像图片加载流程 先从内存取,内存没有从本地文件取,本都文件没有就请求服务器。一旦哪个环节获取到了数据,立刻停止后面的流程

Observable.concat<String>(ob1, ob2, ob3)
          .firstElement()
          .subscribeOn(Schedulers.io())
          .subscribe {
              Log.d("concat-结果", " ${Thread.currentThread().name} ")
          }
  }

运行结果为:

concat-数据源1:  RxCachedThreadScheduler-1 
concat-结果:  RxCachedThreadScheduler-1 

你可能感兴趣的:(Java,android)