RxJava performing operation on a list and returning an observable

痴心易碎 提交于 2019-12-07 08:29:06

问题


I'm new to RxJava (specifically, RxJava2) and I'm having some trouble with what seems to be a relatively easy operation. I need to get some data from a db, iterate through the data (it is represented as a list), perform an operation on each item, wrap the data in another object and return. This is what I have so far:

mDataManager
    .getStuffList(id)
    .flatMapIterable(listOfStuff -> listOfStuff)
    .flatMap(item ->
         mDataManager
             .performCount(id, item.getTitle())
             .doOnNext(item::setCounter)
             .takeLast(1)
             .map(counter -> item))
    .toList()
    .toObservable()
    .flatMap(listOfStuff -> Observable.just(new StuffWrapper(listOfStuff));

The problem I'm having is that my data manager calls never complete. The idea was that whenever the underlying data changes, the UI changes as well. However, without completing those calls, toList() won't emit the event.


回答1:


In RxJava 2, toList returns a Single: it's equivalent to an Observable with exactly one item. You can convert it to an Observable by adding .toObservable, but that isn't needed that often.

Regarding your other changes, what do you mean by whenever the underlying data changes? Does your data manager notify you on data changes?

Edit: if your mDataManager.getStuffList(id) call returns an Observable that emits multiple items (that is, it never completes but always emits the latest data set after a change), then you need to do something like this:

mDataManager
.getStuffList(id)
.flatMap(listOfStuff ->
    Observable
    .from(listOfStuff)
    .flatMap(item ->
         mDataManager
             .performCount(id, item.getTitle())
             .doOnNext(item::setCounter)
             .takeLast(1)
         .map(counter -> item)
         .toList()
    )
)
...


来源:https://stackoverflow.com/questions/41938046/rxjava-performing-operation-on-a-list-and-returning-an-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!