我想在android中用RxJava替換我的AsyncTask。我現在的AsyncTask是這樣的:我想使用RxJava的進度條,就像你可以用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());
}
}
如何模仿onPreExecute()方法中的AsyncTask,我啓動progressDialog?
使用doOnNext()方法 – Tuby
@Tuby你如何做到這一點? –
查找此類https://github.com/TwistedEquations/android-rxmvp-tutorial/blob/master/app/src/main/java/com/twistedeqations/rxmvp/sample/activities/home/mvp/HomePresenter.java,它使用doOnNext將showLoading設置爲true,這將啓用進度條,您可以在此方法中調用ringProgressDialog.show()。 – Tuby