Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a suspend function inside a normal function

I want to call blocking a suspend function in a normal function, but does not block Thread to finishing suspend function and then return Response

override fun intercept(chain: Interceptor.Chain): Response {

    // getSession is a suspend function
    val session = sessionProvider.getSession()

    return chain.proceed(
        chain
            .request()
            .newBuilder()
            .addHeader("Authorization", "${session.token}")
            .build()
    )
}
like image 302
beigirad Avatar asked Jun 01 '19 19:06

beigirad


People also ask

Can you run a suspend function outside of a coroutine or another suspending function?

One of the most important points to remember about the suspend functions is that they are only allowed to be called from a coroutine or another suspend function.

Is suspend function async?

I am referring to the suspend keyword. It is not the same as async.

Can coroutines be suspended and resumed?

Coroutines can suspend themselves, and the dispatcher is responsible for resuming them. To specify where the coroutines should run, Kotlin provides three dispatchers that you can use: Dispatchers. Main - Use this dispatcher to run a coroutine on the main Android thread.

What is the difference between suspending vs blocking?

Hunting to know BLOCKING vs SUSPENDINGA process is blocked when there is some external reason that it can not be restarted, e.g., an I/O device is unavailable, or a semaphore file is locked. A process is suspended means that the OS has stopped executing it, but that could just be for time-slicing (multitasking).


1 Answers

This looks like you are implementing an OkHttp interceptor, so I am hoping that intercept() is being called on a background thread.

If so, use runBlocking():

override fun intercept(chain: Interceptor.Chain): Response {

    // getSession is a suspend function
    val session = runBlocking { sessionProvider.getSession() }

    return chain.proceed(
        chain
            .request()
            .newBuilder()
            .addHeader("Authorization", "${session.token}")
            .build()
    )
}

runBlocking() will execute the suspend function, blocking the current thread until that work is complete.

like image 162
CommonsWare Avatar answered Sep 28 '22 01:09

CommonsWare