1. 程式人生 > >Rxjava,Map操作符的例子

Rxjava,Map操作符的例子

Map的作用

Map操作符的作用就是將Observable所傳送送的資訊進行格式轉換或者處理,然後轉變為另外一個型別,傳送給Observer

匯入依賴

    def retrofit_version = "2.1.0"
    def rxjava_version = "2.0.1"

    //RxJava的依賴包
    implementation 'io.reactivex.rxjava2:rxjava:' + rxjava_version
    //RxAndroid的依賴包
    implementation 'io.reactivex.rxjava2:rxandroid:' + rxjava_version

    //RxBinding
    implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'

最簡單的例子


        Observable
                //傳入兩條資料
                .create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> e) throws Exception {
                        e.onNext("1");
                        e.onNext("2");
                        e.onComplete();
                    }
                })
                //將String型別轉化為Integer
                .map(new Function<String, Integer>() {
                    @Override
                    public Integer apply(String s) throws Exception {
                        return Integer.parseInt(s);
                    }
                })
                //接收資料
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer value) {
                        Log.d(TAG, "onNext: " + (value + 1));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG, "onComplete: ");
                    }
                });


        Observable
                //傳入三條資料
                .just("1", "2", "3")
                //將String型別轉化為Integer
                .map(new Function<String, Integer>() {
                    @Override
                    public Integer apply(String s) throws Exception {
                        return Integer.parseInt(s);
                    }
                })
                //接收資料,消費者
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.d(TAG, "accept: " + (++integer));
                    }
                });

輸出結果

2018-12-03 23:26:36.758 13436-13436/? D/MainActivity: onNext: 2
2018-12-03 23:26:36.758 13436-13436/? D/MainActivity: onNext: 3
2018-12-03 23:26:36.758 13436-13436/? D/MainActivity: onComplete: 
2018-12-03 23:26:36.759 13436-13436/? D/MainActivity: accept: 2
2018-12-03 23:26:36.759 13436-13436/? D/MainActivity: accept: 3
2018-12-03 23:26:36.759 13436-13436/? D/MainActivity: accept: 4