android-Kotlin Rx:必需的使用者,找到KFunction

我正在使用Kotlin Retrofit Rx.我想将请求之一提取为函数:

fun getDataAsync(onSuccess: Consumer<Data>, onError: Consumer<in Throwable>) {
    ApiManager.instance.api
            .getData("some", "parameters", "here")
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                time = System.currentTimeMillis()
                onSuccess.accept(it)
            }, onError)
}


fun onButtonClick() {
    getDataAsync(this::onSuccess, this::onError)
}

private fun onSuccess(data: Data) {}

private fun onError(throwable: Throwable) {}

我在getDataAsync(this :: onSuccess,this :: onError)行中收到错误:

Type mismatch: inferred type is KFunction1<@ParameterName Data, Unit> but Consumer<Data> was expected

Type mismatch: inferred type is KFunction1<@ParameterName Throwable, Unit> but Consumer<in Throwable> was expected

如何解决?

最佳答案
不用传递Consumer作为参数,您可以传递一个函数

fun getDataAsync(onSuccess: (Data) -> Unit, onError: (Throwable) -> Unit) {
     ApiManager.instance.api
        .getData("some", "parameters", "here")
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({
            time = System.currentTimeMillis()
            onSuccess(it)
        }, onError)
}


fun onButtonClick() {
   getDataAsync(this::onSuccess, this::onError)
}

private fun onSuccess(data: Data) {}

private fun onError(throwable: Throwable) {}

转载注明原文:android-Kotlin Rx:必需的使用者,找到KFunction - 代码日志