忘掉RxJava! Kotlin異步請求DSL更優雅

實現移動互聯網app離不開調用Restful APIs,以及等待Callback, 處理Response, 更新UI等套路。感謝Retrofit, RxJava等框架,你們應該已經習慣了這樣的代碼:bash

myCompositeDisposable?.add(requestInterface.getData()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(this::handleResponse))
 
}
複製代碼

雖然也算簡短,卻遠遠稱不上簡明。9102年了,咱們有更好的選擇嗎? Yes! 你們來感覺下這個:app

{
            getData()
                .onSuccess { data ->
                    Toast.makeText(this@MainActivity, "Successfully Fetched ${data?.size} Items", Toast.LENGTH_LONG)
                        .show()
                }
                .onError { error ->
                    Toast.makeText(this@MainActivity, "Failed!! -- $error", Toast.LENGTH_LONG).show()
                }
} 
複製代碼

有點魔幻是吧?其實並不難實現,請看這段泛型化代碼:框架

sealed class AsyncResult<out T : Any>

data class AsyncSuccess<out T : Any>(val data: T?) : AsyncResult<T>()

data class AsyncError(val error: String?) : AsyncResult<Nothing>()

inline fun <T : Any> AsyncResult<T>.onSuccess(action: (T?) -> Unit): AsyncResult<T> {
    if (this is AsyncSuccess) action(data)
    return this
}

inline fun <T : Any> AsyncResult<T>.onError(action: (String) -> Unit) {
    if (this is AsyncError && error != null) action(error)
}
複製代碼

若是沒有豁然開朗, 請等我隨後一一道來:)ui

相關文章
相關標籤/搜索