Rxjava返回LiveData列表

时间:2018-02-19 12:30:21

标签: android kotlin rx-java android-architecture-components android-livedata

您好我正在尝试使用rxjava以及在返回之前使用Map进行转换的LiveData。然而,它说我需要从地图内部返回一些东西。

我尝试回复Single.just(pianoStorage.getAllFavItems())并抱怨你不允许退货吗?

override fun getFavouriteItems() : Single<LiveData<MutableList<Items>>>{
        //check if db has offers
        if (storage.getAllFavItems().value!!.isEmpty()){
             getAllFavItems().map {
                 {offers : ItemsResponse ->
                     storage.saveAllItemsLists(offers)
                     Single.just(storage.getAllFavItems())
                 }
             }.subscribe(
                     {offers ->
                         return@subscribe
                     }
             )
        }else{
            return Single.just(storage.getAllFavItems())
        }
    }

下面的代码基本上检查我的持久数据库,如果我有一些项目,如果没有,使用改造从网络中获取它(getAllFavItems())

此网络电话获取所有项目列表,然后我需要做的是先将其保存到存储中,然后使用以下内容从中获取最喜欢的项目:

@Query("SELECT * FROM items WHERE state = 'Fav'")
    fun getAllFavItems(): LiveData<MutableList<Item>>

2 个答案:

答案 0 :(得分:1)

如果您将DAO定义更改为:

@Query("SELECT * FROM items WHERE state = 'Fav'")
fun getAllFavItems(): Flowable<MutableList<Item>>

您可以这样做:

getAllFavItems()
    .flatMap({
        if(it.isEmpty()) {
            getAllFavItems().toFlowable(BackpressureStrategy.XXX)
                .doOnNext({storage.saveAllItemsLists(it)})
                .map {/*TODO: convert from ItemsResponse to List<Item>*/}
        } else {
            Flowable.just(it)
        }
    })

代码会对喜欢的项目进行更改。如果有0个最喜欢的项目,它将调用getAllFavItems()函数并将结果插入到db中(插入结果将导致getAllFavitems()再次发出)。

答案 1 :(得分:0)

更改为:

getAllFavItems().map { offers : ItemsResponse ->
    storage.saveAllItemsLists(offers)
    Single.just(storage.getAllFavItems())
}

{内有两次}map