其他分享
首页 > 其他分享> > android-Kotlin Rx:必需的使用者,找到KFunction

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

作者:互联网

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

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


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

private fun onSuccess(data: Data) {}

private fun one rror(throwable: Throwable) {}

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

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, one rror: (Throwable) -> Unit) {
     ApiManager.instance.api
        .getData("some", "parameters", "here")
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({
            time = System.currentTimeMillis()
            onSuccess(it)
        }, one rror)
}


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

private fun onSuccess(data: Data) {}

private fun one rror(throwable: Throwable) {}

标签:rx-android,kotlin,retrofit,android
来源: https://codeday.me/bug/20191109/2012991.html