在更新关于RxJava / RxAndroid进度的UI时发出单个项目

问题描述 投票:2回答:1

我目前正在尝试在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。因此,我最终完成了以下实现。我将ProgressInfoResult的通过合并到了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中的实现/概念正确还是错误?

尽管可以,但是我个人觉得上面的实现对我来说是奇怪和错误的。由于该任务最终只是尝试进行一些计算并得出一个项目-ResultProgressInfo的发射像“边”一样,而不是“主要”东西。我应该用Single.create()实现它。但是,如果这样做,我将无法想到将任何ProgressInfo传递到我的UI的任何方法。

问题2:在此过程中更新UI时,是否有更好的主意/方式来发出单个项目?

如果是,您将如何在RxJava中实现此逻辑?您能告诉我您的代码/示例吗?

java android rx-java reactive-programming rx-android
1个回答
0
投票
问题1:我在RxJava中的实现/概念正确还是错误?
© www.soinside.com 2019 - 2024. All rights reserved.