我想在Android中用RxJava替换我的AsyncTask。 我目前的AsyncTask是这样的:
public class ProgressBarAsyncTask extends AsyncTask<Void,Void,Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
ringProgressDialog = ProgressDialog.show(context,"MyProgressBarTitle","Working please wait",true, false);
}
@Override
protected Void doInBackground(Void... void) {
//do work
myTask();
return null;
}
@Override
protected void onPostExecute(Void void) {
super.onPostExecute();
ringProgressDialog.dismiss();
}
}
这是我的RxJava替代方案:
public static Observable<Void> getObservable(final Context context,final String... params) {
return Observable.defer(new Func0<Observable<Void>>() {
@Override
public Observable<Void> call() {
return Observable.just(myTask());
}
});
}
public static Subscriber<Void> getSubscriber() {
Subscriber<Void> subscriber = new Subscriber<Void>() {
@Override
public void onCompleted() {
ringProgressDialog.dismiss();
}
@Override
public void onError(Throwable e) {
Log.d(TAG,e.toString());
}
@Override
public void onNext(Void aVoid) {
manipulateData();
}
};
return subscriber;
}
我的活动:
public class MainActivity extends Activity {
private ProgressDialog ringProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GetNumberObservable.Observable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()))
.subscribe(getSubscriber());
}
}
我该如何模仿AsyncTask中的onPreExecute()方法,在其中启动progressDialog?