Android响应式编程开发RxAndroid(3):map
RxJava中的map通过Function(函数)做一次结果转换,例如把输入源的数据转换处理成大写:
package zhangphil.app;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends Activity {
//假设一个数据源
private String TAG = "zhangphil";
Observer<String> observer = new Observer<String>() {
@Override
public void onSubscribe(Disposable d) {
//Log.d(TAG, d.toString());
}
@Override
public void onNext(String s) {
Log.d(TAG, "onNext - Start");
Log.d(TAG, String.valueOf(s));
Log.d(TAG, "onNext - End");
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete");
}
@Override
public void onError(Throwable e) {
Log.e(TAG, e.toString(), e);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//为一个数据源增加一个观察者
//观察者是observer,observer吐出观察到的数据
Observable
.just("zhang", "phil", "@", "csdn")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(function)
.subscribe(observer);
}
private Function<String, String> function = new Function<String, String>() {
@Override
public String apply(String s) throws Exception {
return s.toUpperCase();
}
};
}
代码运行结果输出:
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onNext - Start
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: ZHANG
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onNext - End
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onNext - Start
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: PHIL
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onNext - End
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onNext - Start
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: @
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onNext - End
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onNext - Start
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: CSDN
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onNext - End
03-01 20:32:09.354 1581-1581/zhangphil.app D/zhangphil: onComplete
附录:
1,《Android响应式编程RxAndroid(1):简单例程》链接地址:http://blog.csdn.net/zhangphil/article/details/58593782
2,《Android响应式编程开发RxAndroid(2):简单例程的Android改造 》链接地址:http://blog.csdn.net/zhangphil/article/details/58597372