Rxjava2

1、创建被观察者Flowable:

  Flowable flowable = Flowable.create(new FlowableOnSubscribe() {
            @Override
            public void subscribe(FlowableEmitter e) throws Exception {
                e.onNext("Hello Rxjava2");
                e.onComplete();
            }
        }, BackpressureStrategy.BUFFER);

创建观察者:

Subscriber stringSubscriber = new Subscriber() {
            @Override
            public void onSubscribe(Subscription s) {
                //需要调用request方法,不然onNext,onComplete不会执行
                s.request(Integer.MAX_VALUE);

            }

            @Override
            public void onNext(String s) {

                Log.d(TAG,s);
            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onComplete() {

            }
        };

订阅事件:

flowable.subscribe(stringSubscriber);

2、简单写法:

Flowable<String> flowable1 = Flowable.just("Hello Rxjava2");

        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(@NonNull String s) throws Exception {
                Log.d(TAG,s);
            }
        };
        flowable1.subscribe(consumer);

3、创建观察者Observable

 Observable observable = Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter e) throws Exception {
                e.onNext("h");
                e.onNext("e");
                e.onNext("l");
                e.onNext("l");
                e.onNext("o");
                e.onComplete();
            }
        });

创建观察者:

Observer observer = new Observer() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

订阅事件:

observable.subscribe(observer);

Disposable:可中断事件的接收,但是不中断事件的发送。
可以创建一个compositeDisposable对象,统一管理Disposable:

 CompositeDisposable compositeDisposable = new CompositeDisposable();

        compositeDisposable.add(Observable.just("hello")
                .subscribe(new Consumer() {
                               @Override
                               public void accept(@NonNull String s) throws Exception {

                               }
                           },
                        new Consumer() {
                            @Override
                            public void accept(@NonNull Throwable throwable) throws Exception {

                            }
                        }));
compositeDisposable.clear();

你可能感兴趣的:(Rxjava2)