Philipp
Philipp

Reputation: 25

Kotlin Coroutine returning after response.await()

I am trying to make an android app connecting to api, and for that I am using Kotlin Coroutines and Retrofit. I was following this tutorial (https://android.jlelse.eu/android-networking-in-2019-retrofit-with-kotlins-coroutines-aefe82c4d777) trying to setup my own api, but I stumbled on a problem. I can't get any data from api because I can't process response.

I don't know much about coroutines, so I don't understand whats the problem here. If I run debug and go line by line it is working perfectly each time, but if I run the app, it only prints TestPoint1. Also it doesn't throw any error and response is always 200 OK. I have tried to combine

val standings = service.getStandings()

and

val response = standings.await()

into one line, after which it doesn't work on debug either. It continues on code after launched coroutine.

val service = ApiFactory.footballApi

GlobalScope.launch(Dispatchers.Main) {
    val standings = service.getStandings()
    try {
        Log.d("TAG", "TestPoint1")
        val response = standings.await()
        Log.d("TAG", "TestPoint2")
        if(response.isSuccessful){
            //store data
        }else{
            Log.d("MainActivity ",response.errorBody().toString())
        }
    }catch (e: Exception){
        Log.d("TAG", "Error")
    }
}

Upvotes: 1

Views: 1339

Answers (1)

apksherlock
apksherlock

Reputation: 8371

Switch the Dispatchers.Main to Dispatchers.IO . You can't make that request on the main thread . The coroutines require a coroutine context in order to know in what thread they are going to run . For that , the Dispatchers class offer you some options . Currently you are making the request in the Dispatchers.Main which you cannot do because fetching data from the API , requires another thread . IO is the right thread for network calls .

Note :

Also please check : Internet permission, Internet connection .

Upvotes: 1

Related Questions