Hey I want to call *`api`* from *`object`* class. ...
# coroutines
v
Hey I want to call
api
from
object
class. I am new in Coroutines. That API call should be executer concurrently and app's flow should not wait for result of that call. I tried some code, but i am not sure is it correct way of doing it or not. Also i got a error`Process: com.dimen.app, PID: 12496`
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1605)
Copy code
private fun setupLogout() {
    logoutButton.setOnClickListener {
        LoginHelper.logout()
    }
}
fun logout() {
    logD("logout")
    deleteSession()
    .... more function
} 
private fun deleteSession() {
    runBlocking {
        Tokenclass.getToken()?.let {
            logE("token ::-> $it")
            apiCall.deleteSession(it).execute()
        }
    }
}
u
use Retrofit, not .execute() which is a synchronous call. And also runBlocking mostly defeats the point of coroutines, since youre blocking main thread, which is a no no
v
Yes i am using retrofit
n
You aren't giving retrofit an API that can use coroutines. You need your interface to look more like:
Copy code
interface MyApi {
    @DELETE("sessions/delete/{id}")
    suspend fun deleteSession(@Path("id") sessionId: String)
}
You should not be calling runBlocking from main thread. Code is likely to hang or ANR. Generally, you want to start coroutines using
lifecycleScope.launch { ... }
. This starts the coroutine and then returns immediately without waiting for the coroutine to finish.