Reputation: 509
I came across RxJava for android and it's a good library. I'm a beginner and i understand how it works but i have some trouble converting my old codes to RxJava style programming.
Below is my old code I'm using to populate my arraylist of objects.
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;
}
What I want is to convert this method into an Observable and to take advantage of RxJava features.
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>
}
I'm currently stuck how to return the object into Observable or should be my method return an Observable<ArrayList<AppModel>>>
instead.
Upvotes: 3
Views: 1325
Reputation: 1862
you should use map instead of 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;
}
});
}
and if you want to return list instead of emit each item add this after map:
.toList();
Upvotes: 3