Android-->RxJava2更新体验

截止日前最新版2017-3-15:
RxJava

compile 'io.reactivex:rxjava:1.2.7'
compile 'io.reactivex:rxandroid:1.2.1'

RxJava2

compile "io.reactivex.rxjava2:rxjava:2.0.7"
compile "io.reactivex.rxjava2:rxandroid:2.0.1"


1:create操作改变
Rxjava

CompositeSubscription compositeSubscription = new CompositeSubscription();
Observable observable = Observable.create(new Observable.OnSubscribe() {
    @Override
    public void call(Subscriber subscriber) {
        subscriber.onNext("1");
        subscriber.onNext("2");
        //e.onComplete();
        subscriber.onError(new NullPointerException());
    }
});
Subscription subscribe = observable.subscribe(new Observer() {
    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onNext(String s) {

    }
});

//取消订阅
subscribe.unsubscribe();
//或者
compositeSubscription.add(subscribe);
compositeSubscription.unsubscribe();

RxJava2

final CompositeDisposable compositeDisposable = new CompositeDisposable();
Observable observable = Observable.create(new ObservableOnSubscribe() {
    @Override
    public void subscribe(ObservableEmitter e) throws Exception {
        e.onNext("1");
        e.onNext("2");
        //e.onComplete();
        e.onError(new NullPointerException());
    }
});

//subscribe方法返回void类型
observable.subscribe(new Observer() {
    @Override
    public void onSubscribe(Disposable d) {
        compositeDisposable.add(d);
    }

    @Override
    public void onNext(String s) {

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }
});

compositeDisposable.dispose();

2:新增Flowable

Flowable stringFlowable = Flowable
       .create(new FlowableOnSubscribe() {
           @Override
           public void subscribe(FlowableEmitter e) throws Exception {
               e.onNext("1");
               e.onNext("2");
               e.onComplete();
               //e.onError(new NullPointerException());
           }
       }, BackpressureStrategy.ERROR)
       .subscribeOn(Schedulers.newThread())
       .observeOn(Schedulers.newThread());

stringFlowable.subscribe(new Subscriber() {
   @Override
   public void onSubscribe(Subscription s) {
       //s.request(1);
       // 参数表示接受多少次onNext回调.
       // 当onNext回调次数和这个参数不一致时, 则通过BackpressureStrategy.ERROR参数决定之后的处理
       // 不调用等价于request(0).
       // 典型的错误MissingBackpressureException异常
       // 注意: Flowable请尽量在异步线程使用,否则很容易出现MissingBackpressureException异常
   }

   @Override
   public void onNext(String s) {
   }

   @Override
   public void onError(Throwable t) {
   }

   @Override
   public void onComplete() {
   }
});

更详细的解释移步至:http://www.jianshu.com/p/9b1304435564


至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.

你可能感兴趣的:(Android-->RxJava2更新体验)