【问题标题】:Iterate through a list using rxjava2使用 rxjava2 遍历列表
【发布时间】:2018-05-26 08:13:44
【问题描述】:

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

谢谢!

【问题讨论】:

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


    【解决方案1】:

    使用 Observable.fromIterable 迭代 List 中的所有项目,并在后台线程上使用 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());
                    }
                });
    

    【讨论】:

    • 感谢您的回复。是否会对每个项目应用长操作?
    • 是的,它将应用于所有项目。
    • 谢谢@Abu Yousuf。会试一试!
    • accept() 与 onNext() 有何不同?我也可以在这里使用 onNext() 对。
    猜你喜欢
    • 2017-06-15
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多