我目前正在尝试在Android中学习RxJava。我需要一些指南。目前,我正在尝试将下面的AsyncTask重写为RxJava:
public class MyAsyncTask extends AsyncTask<Void, ProgressInfo, Result> {
@Override
protected Result doInBackground(Void... void) {
//Long running task
publishProgress(progressInfo);
//Long running task
return result;
}
@Override
protected void onProgressUpdate(ProgressInfo... progressInfo) {
//Update the progress to UI using data from ProgressInfo
}
@Override
protected void onPostExecute(Result res) {
//Task is completed with a Result
}
}
在上面显示的AsyncTask方法中,我可以使用onProgressUpdate
方法来更新有关进度的UI,将所需的每个数据打包到ProgressInfo
中并在onProgressUpdate
中反映UI。任务结束后,Result
将从doInBackground
传递到onPostExecute
。
但是,当我尝试使用RxJava实现此功能时,我很难处理它。由于我无法将任何参数传递给Observer中的onComplete
。因此,我最终完成了以下实现。我将ProgressInfo
和Result
的通过合并到了onNext
中。
Observable.create(emitter -> {
//Long running task
emitter.onNext(progressInfo);
//Long running task
emitter.onNext(result);
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object -> {
if(object instanceof ProgressInfo){
//Update the progress to UI using data from ProgressInfo
}else if(object instanceof Result){
//Task is completed with a Result
}
});
问题1:我在RxJava中的实现/概念正确还是错误?
尽管可以,但是我个人觉得上面的实现对我来说是奇怪和错误的。由于该任务最终只是尝试进行一些计算并得出一个项目-Result
。 ProgressInfo
的发射像“边”一样,而不是“主要”东西。我应该用Single.create()实现它。但是,如果这样做,我将无法想到将任何ProgressInfo
传递到我的UI的任何方法。
问题2:在此过程中更新UI时,是否有更好的主意/方式来发出单个项目?
如果是,您将如何在RxJava中实现此逻辑?您能告诉我您的代码/示例吗?
问题1:我在RxJava中的实现/概念正确还是错误?