gpt4 book ai didi

android - 使用 rxjava2 遍历列表

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:05 25 4
gpt4 key购买 nike

我有一个自定义对象列表 ( 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());
}
});

关于android - 使用 rxjava2 遍历列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50540746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com