簡體   English   中英

Kotlin + Rx:需要消費者,找到KFunction

[英]Kotlin + Rx: required Consumer, found 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)行中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

怎么解決?

問題是,當您提供方法引用時,您的方法getDataAsync需要兩個參數的Consumer類型的對象。 請注意,Java中發生了同樣的錯誤。

為了解決這個問題,您可以將getDataAsync兩個參數聲明為函數引用,或者創建Consumer的實現。

第一解決方案

fun getDataAsync(onSuccess: (Data) -> Unit, onError: (Throwable) -> Unit) {

}

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


private fun onSuccess(data: Data) {

}

private fun onError(throwable: Throwable) {}

二解決方案

fun getDataAsync(onSuccess: Consumer<Data>, onError: Consumer<in Throwable>) {

}

fun onButtonClick() {
    getDataAsync(Consumer { data ->
        // do something
    }, Consumer { throwable ->
        // do something
    })
}

您可以只傳遞一個函數,而不是將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) {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM