Tidy up Kotlin Android RxJava 2 callback

heri sulistiyanto
2 min readJan 27, 2018

--

In the beginning migration process from Java to Kotlin, i’m still using many interface callback to handle the response from RxJava, because this is the proper way in Java in most case as far as i know.

Previously i write my code like this :

fun getAllCurrency(callback: NetworkCallback<List<CurrencyModel>, Throwable>): Disposable {
return networkServices.getAllCurrency()
.uiSubscribe(
onNext = { callback.onSuccess(it) },
onError = { callback.onError(it) }
)
}

interface NetworkCallback<in T, in R> {
fun onSuccess(response: T)
fun onError(error: R)
}

And yes, it works but when i invoke the method, i have to make anonymous class to implement the interface :

disposables.add(service.getAllCurrency(object : NetworkCallback<List<CurrencyModel>, Throwable> {
override fun onSuccess(response: List<CurrencyModel>) {
// handle success response
}

override fun onError(error: Throwable) {
// handle error response
}

}))

this will quite mess when we put bunch of code. But lately i change my code using higher order function instead :

fun getAllCurrency(onSuccess: (List<CurrencyModel>) -> Unit,
onError: (Throwable) -> Unit): Disposable {
return networkServices.getAllCurrency()
.uiSubscribe(
onNext = { onSuccess(it) },
onError = { onError(it) }
)
}

I pass success and error function handler as parameter, so when i invoke the function, it will gonna be like this :

disposables.add(service.getAllCurrency(
onSuccess = { response ->
// handle success response List<CurrencyModel>
},
onError = { error ->
// handle error response Throwable
}))

It looks way better and tidy IMO.

kotlin is awesome

Thank you for your time to read this article, and this is my first article by the way, and sorry for my bad English :)

thank you

--

--