RxJava2操作符Map
阿新 • • 發佈:2019-02-11
//RxJava2 Map操作符 /** * Map操作符的作用就是將Observable所傳送送的資訊進行格式轉換或者處理, * 然後轉變為另外一個型別,傳送給Observer */ Observable.create(new ObservableOnSubscribe<Integer>() { int i = 0; @Override public void subscribe(@NonNull ObservableEmitter<Integer> e) throws Exception { while (i < 3) { Log.d("MainActivity", "Observable on " + Thread.currentThread().getName() + " emit " + i); e.onNext(i); i++; } } }).subscribeOn(Schedulers.io()) //map操作符,Function<Object,Object>,只要型別為Object的子類就可以進行轉換 .map(new Function<Integer, String>() { //這個就是轉換的函式,返回的是轉換結果 @Override public String apply(@NonNull Integer integer) throws Exception { return "This is a String Type:" + integer; } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String s) { //這裡接收的就是一個String型別了 Log.d("MainActivity", "Observer on " + Thread.currentThread().getName() + " Receive:" + s); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } });