Returning data from asynchronous API call in Kotlin


I am creating an app accessing data from an REST API. I have login page, which accepts email address and password and call a API method to get access token. I need embed the access token in subsequent API call to get the data. I was able to connect to the API and get the access token not in the first attempt because I am making asynchronous call to the API. So first attempt the function returns no token till the asynchronous call resolves and token is available. What change I need to make in below code to return AuthenticationToken object with access token details.

private fun getToken(email: String, password : String) {

    var returnVal: AuthenticationToken = AuthenticationToken(access_token = "", token_type = "", expires_in = "")
    val mediaType = MediaType.parse("application/x-www-form-urlencoded")
    val body = RequestBody.create(mediaType, "username=$email&password=$password&grant_type=password")
    val request = Request.Builder()
        .method("POST", body)
        .addHeader("Authorization", "Basic xxxxxxxxxxxx")
        .addHeader("Content-Type", "application/x-www-form-urlencoded")
    //Log.d("MainActivity", "$url")

     client.newCall(request).enqueue(object : Callback {
        override fun onResponse(call: Call, response: Response) {
            if(response.isSuccessful) {
                val body = response?.body()?.string()
                val json = JSONObject(body)
                val token = json.getString("access_token")
                val type = json.getString("token_type")
                val expiry = json.getString("expires_in")
                val gson = GsonBuilder().create()
                authToken = gson.fromJson(body,
                returnVal = AuthenticationToken(access_token = token, token_type = type, expires_in = expiry)
                Log.d("MainActivity", "Return value in OnResponse method is $returnVal")

        override fun onFailure(call: Call, e: IOException) {
            println("Failed to execute the request")
            returnVal = AuthenticationToken(access_token = "", token_type = "", expires_in = "")
    Log.d("LoginDataSource","Return value is $returnVal")
    return returnVal

I highly recommend using Kotlin Coroutines and Retrofit.

Here’s a small guide on using them together: Using Retrofit with Kotlin Coroutines in Android