将Arraylist <object>方法转换为RxJava Observable

时间:2018-01-15 15:51:42

标签: java android arraylist rx-java rx-android

我遇到了RxJava for android,它是一个很好的库。我是一个初学者,我理解它是如何工作的,但我将旧代码转换为RxJava风格编程时遇到了一些麻烦。

下面是我用来填充对象arraylist的旧代码。

public ArrayList<AppModel> getMyAppList(PackageManager pm, List<ApplicationInfo> list){
        ArrayList<AppModel> temp = new ArrayList<>();


        for(int d=0;d<list.size();d++){
            ApplicationInfo infos = list.get(d);
            AppModel model = new AppModel();
            model.set_id(d);
            model.setApp_name(""+infos.loadLabel(pm));
            model.setPackage_name(""+infos.packageName);
            model.setIcon(infos.loadIcon(pm));
            //Log.e("resolve "," "+infos.loadIcon(pm));
            temp.add(model);
        }

        return temp;
    }

我想要的是将此方法转换为Observable并利用RxJava功能。

public Observable<AppModel> getMyAppList(PackageManager pm, List<ApplicationInfo> list){



        return Observable
                .from(list)
                .subscribeOn(Schedulers.computation())
                .doOnNext(new Action1<ApplicationInfo>() {
                    @Override
                    public void call(ApplicationInfo applicationInfo) {
                        AppModel mm = new AppModel();
                        mm.set_id(applicationInfo.hashCode());
                        mm.setApp_name(""+applicationInfo.loadLabel(pm));
                        mm.setPackage_name(""+applicationInfo.packageName);
                        mm.setIcon(applicationInfo.loadIcon(pm));


                        //add the models to a list

                    }
                }).//return as Observable<AppModel>
    }

我目前仍然坚持如何将对象返回到Observable,或者应该是我的方法返回Observable<ArrayList<AppModel>>>

1 个答案:

答案 0 :(得分:1)

你应该使用map而不是doOnNext

public Observable<AppModel> getMyAppList(final PackageManager pm, List<ApplicationInfo> list){



    return Observable
            .from(list)
            .subscribeOn(Schedulers.computation())
            .map(new Func1<ApplicationInfo, AppModel >() {
                @Override
                public AppModel call(ApplicationInfo applicationInfo) {
                    AppModel mm = new AppModel();
                    mm.set_id(applicationInfo.hashCode());
                    mm.setApp_name(""+applicationInfo.loadLabel(pm));
                    mm.setPackage_name(""+applicationInfo.packageName);
                    mm.setIcon(applicationInfo.loadIcon(pm));

                    return mm;
                }
            });
}

如果你想返回列表而不是发出每个项目,请在map:

之后添加
.toList();