我有一个自定义对象列表 ( List<Item> itemsList
)。这是我的自定义类:
public class Item {
private String itemId;
private String itemName;
}
初始列表只有itemName; itemId 将为空。我想遍历列表并为每个项目添加一个 itemId,然后使用新列表,我需要对列表中的每个项目执行某种长时间操作。
for(Item item : itemsList){
item.setitemId = getUniqueId(); //getUniqueId() returns an unique id
doSomeLongOperation(item);
}
我是 rxjava 运算符的新手。请帮助我了解如何使用 rxjava2 实现相同的目标。
谢谢!
使用 Observable.fromIterable
迭代列表中的所有项目,并在后台线程上使用 Subscribe
进行后台工作,然后使用 Map
运算符更新您的Item
并进行长时间运行的工作。完成后返回你需要的东西。
示例代码:
Observable.fromIterable(itemList)
.subscribeOn(Schedulers.io())
.map(new Function<Item, Item>() {
@Override
public Item apply(Item item) throws Exception {
item.setItemId("Id: " + System.currentTimeMillis());
Log.i(TAG, "In Map Item: " + item.toString());
// do some long operation and return
return item;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Item>() {
@Override
public void accept(Item item) throws Exception {
Log.i(TAG, "Item: " + item.toString());
}
});
我是一名优秀的程序员,十分优秀!