Android响应式编程RxAndroid(1):简单例程
响应式Android编程开发,在github上的项目地址:https://github.com/ReactiveX/RxAndroid,设计原则类比Java观察者模式,给出一个简单例子,假设一个数据源,观察者观察数据源,然后做出简单的动作比如输出。
测试的MainActivity.java:
测试的MainActivity.java:
package zhangphil.app;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class MainActivity extends Activity {
//假设一个数据源
private String TAG = "zhangphil@csdn";
Observer<List<String>> observer = new Observer<List<String>>() {
@Override
public void onSubscribe(Disposable d) {
//Log.d(TAG, d.toString());
}
@Override
public void onNext(List list) {
Log.d(TAG, "onNext - Start");
for (int i = 0; i < list.size(); i++) {
Log.d(TAG, String.valueOf(list.get(i)));
}
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);
List<String> lists = new ArrayList<>();
for (int i = 0; i < TAG.length(); i++) {
lists.add(String.valueOf(TAG.charAt(i)));
}
//为一个数据源增加一个观察者
//观察者是observer,observer吐出观察到的数据
Observable
.just(lists)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
}
代码运行输出:
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: onNext - Start
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: z
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: h
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: a
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: n
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: g
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: p
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: h
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: i
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: l
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: @
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: c
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: s
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: d
02-28 13:55:00.571 10845-10845/zhangphil.app W/ActivityThread: AppLock checkAppLockState isAppLocked = false pkgName = zhangphil.app showWhenLocked = false
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: n
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: onNext - End
02-28 13:55:00.571 10845-10845/zhangphil.app D/zhangphil@csdn: onComplete