android - 使用 rxjava2 遍历列表

标签 android arraylist rx-java rx-java2 rx-android

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

相关文章:

java - ArrayList容量增量方程

java - 当 A 实现 B Java 时,ArrayList<A> 转换为 ArrayList<B>

android - Rxjava AndroidSchedulers.mainThread() 表示 UI 线程?

android - React-native + Relay.js 的稳定构建

Java - 从多个 ArrayList 中获取值

android - rxjava 和 android.database.contentobserver

java - Observable.zip 和 Observable.timer

android - 为什么 Project/Properties/Android 在 Eclipse 中不起作用?

android - 如何管理 Android Market 中的多语言列表?

android - 如何通过无线连接将爱普生打印机连接到安卓设备