RxAndroid的map通过Function把一个对象转换为另外一个对象,作为结果输出。flatMap则可以通俗的理解为把一个集合元素对象拆分成单个元素对象,然后丢给Observer作为输入。例子:
package zhangphil.app;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import java.util.Arrays;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends Activity {
//假设一个数据源
private String TAG = "zhangphil测试";
private DisposableObserver<String> observer = new DisposableObserver<String>() {
@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);
String[] source = {"zhang", "phil", "@", "csdn"};
List<String> lists = Arrays.asList(source);
Observable
.just(lists)
.subscribeOn(Schedulers.io())//执行任务的线程
.observeOn(AndroidSchedulers.mainThread())//回调发生的线程
.flatMap(function)
.subscribe(observer);
}
// 设置映射函数
private Function<List<String>, Observable<String>> function = new Function<List<String>, Observable<String>>() {
@Override
public Observable<String> apply(List<String> lists) {
String[] strs = new String[lists.size()];
for (int i = 0; i < lists.size(); i++) {
strs[i] = lists.get(i).toUpperCase();
}
return Observable.fromArray(strs);
}
};
}
代码运行结果输出:
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onNext - Start
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: ZHANG
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onNext - End
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onNext - Start
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: PHIL
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onNext - End
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onNext - Start
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: @
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onNext - End
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onNext - Start
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: CSDN
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onNext - End
03-02 10:31:06.606 18037-18037/zhangphil.app D/zhangphil测试: onComplete