Home > database >  How to use await function in coroutine from non-suspended function in Kotlin Android?
How to use await function in coroutine from non-suspended function in Kotlin Android?

Time:06-15

I want to wait for result, but the problem is I want to do this operation in background thread. I researched about this and got to know about async(), but to use async, my actual function should be also suspend, that is not possible, because that actual function is calling from overridden library so I can't make it suspendable!

Code:

 override fun authenticate(route: Route?, response: Response): Request? {
    return when (tokenProvider.isUserLoggedIn() && countOfResponse(response) <= AppConstants.INetworkValues.RETRY_API_LIMIT) {
        true -> {
            authenticateByRefreshToken(response).also {
            LogUtils.d("API Request: $it")}}
        else -> return null
    }
}

    @Synchronized
    private fun authenticateByRefreshToken(response: Response): Request? {
        .....

        //TODO: Here I want to remove runblocking and want to use async
        val newRefreshTokenResponse: Resource<RefreshTokenResponse?> = runBlocking { refreshTokenImpl.refreshToken() }
        
.....
    }

Please help.

CodePudding user response:

Then you can call this function under the scope of Coroutine like

CoroutineScope(Dispactcher.IO).launch{
authenticateByRefreshToken()
// now you can use suspend keyword with further functions
}

CodePudding user response:

A function with this signature:

override fun authenticate(route: Route?, response: Response): Request? {

requires a synchronous result. That means a coroutine will not help you at this task at all. Coroutines are launched asynchronously (but the code inside the coroutine is synchronous). Asynchronous means it will not return a result directly. A launched coroutine returns a Job or Deferred, which you can wait for only inside other coroutines.

You could wrap your coroutine code in runBlocking instead of using launch, but then of course it will block the thread it is called from, so you have not accomplished anything by using a coroutine. runBlocking only makes sense if you have suspend functions that you need to call synchronously without a coroutine, or that you need to run in parallel while still blocking the calling thread.

I don't use Retrofit/OkHttp much, so I'm not exactly sure about this, but from briefly looking at the documentation, this appears to be an interface that you hand over to OkHttp to use. In that case, there is no reason whatsoever for you to attempt to convert it into asynchronous code. OkHttp is the one calling the function, not your own code, so you cannot control what thread it will be called from. That will be up to OkHttp, and presumably, it will sensibly run the code in an appropriate thread (maybe its asynchronous behavior can be configured elsewhere in your OkHttp setup).

  • Related