如何使用RxAndroid压缩Kotlin语言中的少量可观察量

问题描述 投票:5回答:2

大家!我有一些问题。我是RxJava / RxKotlin / RxAndroid的初学者,并且不了解某些功能。例如:

import rus.pifpaf.client.data.catalog.models.Category
import rus.pifpaf.client.data.main.MainRepository
import rus.pifpaf.client.data.main.models.FrontDataModel
import rus.pifpaf.client.data.product.models.Product
import rx.Observable
import rx.Single
import rx.lang.kotlin.observable
import java.util.*


class MainInteractor {

    private var repository: MainRepository = MainRepository()

    fun getFrontData() {

        val cats = getCategories()
        val day = getDayProduct()
        val top = getTopProducts()

        return Observable.zip(cats, day, top, MainInteractor::convert)
    }

    private fun getTopProducts(): Observable<List<Product>> {
        return repository.getTop()
                .toObservable()
                .onErrorReturn{throwable -> ArrayList() }

    }

    private fun getDayProduct(): Observable<Product> {
        return repository.getSingleProduct()
                .toObservable()
                .onErrorReturn{throwable -> Product()}

    }

    private fun getCategories(): Observable<List<Category>> {
        return repository.getCategories()
                .toObservable()
                .onErrorReturn{throwable -> ArrayList() }
    }

    private fun convert(cats: List<Category>, product: Product, top: List<Product>): FrontDataModel {

    }
}

然后我使用MainInteractor :: convert Android studio告诉我接下来

enter image description here

我尝试了很多变体并试图了解它想要什么,但没有成功。请帮助我...最好的问候。

android rx-java kotlin rx-android rx-kotlin
2个回答
14
投票

只需用lambda替换函数引用:

return Observable.zip(cats, day, top, { c, d, t -> convert(c, d, t) })

并且不要忘记明确声明函数的返回类型:

fun getFrontData(): Observable<FrontDataModel> {
    ...

0
投票

您还可以在lambda中显式指定Function3类型:

Observable.zip(cats
               ,day
               ,top
               ,Function3<List<Product>, Product, List<Category>, FrontDataModel> 
                         { cats, day, top -> convert(cats, day, top) }

并使用IntelliJ创意快捷方式alt+enter来显示更多动作并更改高阶函数的显示格式。

enter image description here

为何选择Function3?

如果函数接口有两个输入参数,则它是一个BiFunction,如果它有3个输入则它是一个Function3,列表继续。

© www.soinside.com 2019 - 2024. All rights reserved.