Kotlin + Rx:必需的消费者,找到 KFunction

BAr*_*ell 6 android kotlin retrofit rx-android

我正在使用 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) {}
Run Code Online (Sandbox Code Playgroud)

我得到一个错误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
Run Code Online (Sandbox Code Playgroud)

如何解决?

Kas*_*asi 3

您可以只传递一个函数,而不是将 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) {}
Run Code Online (Sandbox Code Playgroud)