Kotlin provides Coroutines that makes asynchronous task very easy as well as more readable as it reduces nested callback by linear suspend code.
Kotlin Coroutines can transform legacy callback into suspend function which can be called within any Coroutines scope.
Any callback can easily be called within a suspend function by suspendCoroutine feature. The following code shows RemoteDataSource provides data using callback but requestRemoteData() suspend function converts the callback into suspend function.
coroutineScope.launch{
val data = requestRemoteData()
}
suspend fun requestRemoteData() = suspendCoroutine<Data> {
continuation ->
remoteDataSource.requestData {
continuation.resume(it)
}
}
class RemoteDataSource(private val remoteApi: RemoteApi) {
fun requestData(callBack: (Data) -> Unit) {
/*get data from server side*/
remoteApi.getData {
override fun onSuccess(data: Data) {
callBack.invoke(data)
}
}
}
}
In this way we can easily integrate Kotlin Coroutines into our existing callback asynchronous code.
Comentarios