RxJava 从上倒下的链式调用,学习它先掌握下观察者设计模式比较好
A 观察者 B 被观察者
A不需要像警察一样随时随刻的观察B的一举一动。
A 观察者 B 被观察者
A不需要像警察一样随时随刻的观察B的一举一动。
程序员的观察者模式并不需要一直观察、留意被观察者的一举一动,而是采用注册register/订阅subscribe的方式。
在subscribe之间写上两句
.subscribeOn(Schedulers.io())//指定 subscribe() 发生在 IO 线程
.observeOn(AndroidSchedulers.mainThread())//指定 Subscriber 的回调发生在主线程
这种使用方式非常常见,就是所谓的后台线程获取数据,主线程显示信息。
而在表示观察与被观察之间的联系是这样表达的:
被观察者.subscribe(观察者),
举个例子,当我们打开程序,启动页跳转到一个倒计时5个数开始的界面操作。原本没有接触到Rxjava,都是handler来实现的,下面我们来看下Rxjava是怎么实现的呢?
SplashAction:
public class SplashAction extends Activity {
private LinearLayout mLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mLayout= (LinearLayout) findViewById(R.id.splash_logo_layout);
// 获取屏幕宽高度
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
// 引导页logo的手动布局添加
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
(int)((float)width* 0.42F),
(int)((float)height * 0.35F));
params.topMargin = (int)((float)height * 0.15F);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
mLayout.setLayoutParams(params);
rx.Observable.timer(800, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
public void call(Long aLong) {
SplashAction.this.startActivity(new Intent(SplashAction.this,MainActivity.class));
finish();
}
});
}
}
RxJava定时器:timer,Timer操作符创建一个在给定的时间段之后返回一个特殊值的Observable.没有什么其他的,上段代码就是在特定的时间去调转界面,从引导页界面调转到主界面。替代了我们原本Handler的写法,另外附上handler是如何实现的。
mHandler = new Handler();
mHandler.postDelayed(runnable=new Runnable()
{
public void run()
{
Intent intent = new Intent();
intent.setClass(SplashAction.this, LoginAction.class);
SplashAction.this.startActivity(intent);
SplashAction.this.finish();
}
}, 1300);
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
final TextView text = (TextView) findViewById(R.id.tv);
final List<String> list= Arrays.asList("five", "four", "three", "two", "one");
Subscriber<Long> subscriber=new Subscriber<Long>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long l) {
int i = l.intValue();
if (i == list.size()) {
this.unsubscribe();
onCompleted();
}
text.setText(list.get(i));
}
};
Observable.interval(2,1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}
RxJava轮询器:interval,Interval操作符返回一个Observable,它按固定的时间间隔发射一个无限递增的整数序列。上面就是实现已固定时间间隔读取数组内容来达到一个倒计时的效果。