Issue
Here is my code. I have async request which is implemented in SDK . I am using it, I have implemented it simple way calling login providing callback for that async request. My question is it possible if to combine this Async request using RxAndroid or Kotlin Coroutines? As I am going to have a lot of callback chains to avoid it I am thinking to combine with RxJava or Kotlin Coroutines. Any hints of referening to a sample could be goodl
private fun automaticLogin() {
UserAction(username, password).login(AutomaticUserLoginRequest(this))
}
class AutomaticUserLoginRequest()
: UserLoginRequest( object : ILoginResultHandler {
override fun onSuccess(session: ISession) {
}
override fun onError(error: Error) {
}
})```
Solution
You may do something like with the suspendCoroutine
function:
suspend fun automaticUserLoginRequest(): ISession {
return suspendCoroutine<ISession> { cont ->
callUserLoginRequest(object : ILoginResultHandler {
override fun onSuccess(session: ISession) {
cont.resume(session)
}
override fun onError(error: Error) {
cont.resumeWithException(error)
}
}
}
}
You may execute the suspend function from a coroutine. The kotlinx.coroutines-android provides the Dispatchers.UI
for that:
fun someFunction() {
//starts a coroutine, not waiting fro result
launch(Dispatchers.UI) {
val session = automaticUserLoginRequest()
//the execution will resume here once login is done, it can be an exception too
updateUI(session)
}
}
https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-android/README.md
Answered By - Eugene Petrenko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.