gpt4 book ai didi

android - Kotlin + Rx : required Consumer, 找到 KFunction

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:36 25 4
gpt4 key购买 nike

我正在使用 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

如何解决?

最佳答案

您可以传递一个函数,而不是将消费者作为参数传递

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 : required Consumer, 找到 KFunction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com