Search code examples
androidkotlincoroutinesuspendkotlin-coroutines

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()
    )
}

Solution

  • 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.