如何调用observable将其他内容加载到一个对象中,将其转换为另一个可观察对象?

时间:2017-11-16 02:26:14

标签: java android rx-java reactive-programming rx-java2

我有这个MyCollectionInteractor加载来自firebase数据库的所有CollectionItemVO

public interface MyCollectionInteractor extends BaseInteractor{
    Single<List<CollectionItemVO>> load ();
}

CollectionItemVO是:

public class CollectionItemVO {
    String beerId;
    long timestamp;
    int quantity;

    public CollectionItemVO() {
    }


    public CollectionItemVO(String beerId, long timestamp, int quantity) {
        this.beerId = beerId;
        this.timestamp = timestamp;
        this.quantity = quantity;
    }
}

所以我有CollectionItem

public class CollectionItem {

    private final CollectionItemVO itemVOList;
    private final Beer beer;

    public CollectionItem(Beer beer, CollectionItemVO itemVOList) {
        this.beer = beer;
        this.itemVOList = itemVOList;
    }

}

它有一个完整的Beer对象。要加载该对象,我使用其他交互器:

public interface LoadBeerInteractor extends BaseInteractor {
    Flowable<Beer> load(String beerId);
}

我想将这个CollectionInteractor.load调用转换为Observable CollectionItem,我希望使用LoadBeerInteractor.load(beerId)以完整的啤酒对象传递CollectionItem。

对于我研究的内容,我相信可以使用flatmap来实现,但我还没有达到预期的效果。

1 个答案:

答案 0 :(得分:2)

我认为你需要做这样的事情:

MyCollectionInteractor collections = ...
LoadBeerInteractor beers = ...

Flowable<CollectionItem> items = collections.load()
    .toFlowable()
    .flatMapIterable(it -> it) // unpack from Flow<List<T>> to Flow<T>
    .flatMap(it ->
        beers
            .load(it.beerId)
            .map(beer -> new CollectionItem(beer, it))
    )

这可能也有效:

Flowable<CollectionItem> items = collections.load()
    .toFlowable()
    .flatMap(list ->
        Flowable
            .from(list)
            .flatMap(it -> 
                beers
                    .load(it.beerId)
                    .map(beer -> new CollectionItem(beer, it))
            )
    )