1.RxJava 操作符
just、from、defer、interval(间隔)、range(范围)、repeat(重复)、timer
变换操作符
map、flatMap、concatMap、filter(过滤)、skip(跳过前面的元素)、take(指定元素)
2、使用场景
界面防抖动(throttleFirst)
RxView.clicks(mBtnTest2).throttleFirst(1L, TimeUnit.SECONDS).subscribe(new Action1<Void>() {
@Override
public void call(Void aVoid) {
Toast.makeText(MainActivity.this, "button2 clicked", Toast.LENGTH_SHORT).show()
}
定时任务(timer)
private void startTimerTask() {
Observable.timer(2, TimeUnit.SECONDS).subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
Log.d("MainActivity", "start execute task:" + Thread.currentThread().getName());
}
});
周期任务(interval)
private void startIntervalTask() {
Observable.interval(5, TimeUnit.SECONDS).subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
Log.d("MainActivity", "start task:" + Thread.currentThread().getName());
}
});
响应式界面(注册、登录 combineLatest)
EditText mEditUsername = (EditText) findViewById(R.id.editText3)
EditText mEditPwd = (EditText) findViewById(R.id.editText4)
final Button mBtnLogin = (Button) findViewById(R.id.button2)
mBtnLogin.setEnabled(false)
Observable<CharSequence> usernameOb = RxTextView.textChanges(mEditUsername)
Observable<CharSequence> pwdOb = RxTextView.textChanges(mEditPwd)
Observable.combineLatest(usernameOb, pwdOb, new Func2<CharSequence, CharSequence,="" Boolean="">() {
@Override
public Boolean call(CharSequence username, CharSequence pwd) {
return !TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)
}
}).subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean isLogin) {
mBtnLogin.setEnabled(isLogin)
}
线程调度
Observable.just("https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D200/sign=4db5130a073b5bb5a1d727fe06d2d523/cf1b9d16fdfaaf51965f931e885494eef11f7ad6.jpg")
.map(new Func1<String, Drawable>() {
@Override
public Drawable call(String s) {
try {
Drawable src = Drawable.createFromStream(new URL(s).openStream(), "src");
return src;
}catch (IOException e){
}
return null;
}
}).subscribeOn(Schedulers.io()) //发射者 在io 子线程操作
.observeOn(AndroidSchedulers.mainThread()) //接收者 在主线程操作
.subscribe(new Action1<Drawable>() {
@Override
public void call(Drawable drawable) {
if (drawable != null) {
mIvLogo.setImageDrawable(drawable);
}
}
});
网友评论