回调到可观察

时间:2019-09-07 18:36:57

标签: android kotlin mvvm google-cloud-firestore rx-java2

我具有从Cloud Firestore获取文档的功能:

fun getBasicItems(callback: (MutableList<FireStoreBasicItem>) -> Unit) {
    fireStore.collection("BasicItems")
        .get()
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val basicItems = mutableListOf<FireStoreBasicItem>()
                for (document in task.result!!) {
                    val fireStoreBasicItem = document.toObject(FireStoreBasicItem::class.java)
                    basicItems.add(fireStoreBasicItem)
                    callback(basicItems)
                }
            }
        }
}

在我的ViewModel中,我想将其转换为Observable,然后转换为ViewState

private fun loadDataTransformer(): ObservableTransformer<ItemEvent.LoadDataEvent, ItemsViewState> {
    return ObservableTransformer { event ->
        event.map {
                 itemRepository.getBasicItems(){myBasicItemList -> Observable.just(myBasicItemList)}

    }
}

我也用Observable.fromCallable尝试过。我在做什么错了?

编辑:我的解决方案

private fun loadDataTransformer(): ObservableTransformer<ItemEvent.LoadDataEvent, ItemsViewState> {
    return ObservableTransformer { event ->
        event.flatMap {
            Single.create<MutableList<FireStoreBasicItem>> {
                itemRepository.getBasicItems { myBasicItemList ->
                    it.onSuccess(myBasicItemList)
                }
            }.toObservable()
                .map {
                    ItemsViewState.ItemDataState(it)
                }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

如果您只希望列出一个项目,我建议您使用Single而不是Observable。然后,您可以使用Single.create

private fun loadDataTransformer(): Single<ItemsViewState> =
    Single.create { emitter ->
        itemRepository.getBasicItems() { myBasicItemList ->
            val viewState =  // do some transformations
            emitter.onSuccess(viewState)
        }
    }