RxAndrod是Rxjava的android拓展版,常常用于:
1.异步操作,跟asyntask差不多吧。
2.做一些订阅。
项目地址:
https://github.com/ReactiveX/RxAndroid
项目demo
项目有个小demo,简单地展示了其作用,老实说,没看出有什么好用。
package io.reactivex.android.samples;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable;
public class MainActivity extends Activity {
private static final String TAG = "RxAndroidSamples";
private final CompositeDisposable disposables = new CompositeDisposable(); //这个就当他是个组合包吧
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
findViewById(R.id.button_run_scheduler).setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
onRunSchedulerExampleButtonClicked();
}
});
}
@Override protected void onDestroy() {
super.onDestroy();
disposables.clear(); //估计是取消订阅吧
}
void onRunSchedulerExampleButtonClicked() {
disposables.add(sampleObservable()
// Run on a background thread
.subscribeOn(Schedulers.io()) //跑在子线程
// Be notified on the main thread
.observeOn(AndroidSchedulers.mainThread()) //结果展示在主线程,所以下面的回调都在主线程
.subscribeWith(new DisposableObserver<String>() {
@Override public void onComplete() {
Log.d(TAG, "onComplete()");
}
@Override public void onError(Throwable e) {
Log.e(TAG, "onError()", e);
}
@Override public void onNext(String string) {
Log.d(TAG, "onNext() in "+Thread.currentThread().getName());
Log.d(TAG, "onNext(" + string + ")");
}
}));
}
static Observable<String> sampleObservable() { //这个玩意跑在子线程
return Observable.defer(new Callable<ObservableSource<? extends String>>() {
@Override public ObservableSource<? extends String> call() throws Exception {
// Do some long running operation
SystemClock.sleep(5000);
Log.d(TAG, "call() in "+Thread.currentThread().getName());
return Observable.just("one", "two", "three", "four", "five");
}
});
}
}
运行界面与结果:
上面这个例子跟asyntask没多大区别啊,耗时操作在doinbackgroud,结果在onpostresult。估计主要作用还是在订阅吧。