How do I pause execution in Kotlin whilst APIs complete

I am trying to write a simple app in Android Studio using Kotlin. It is a very steep learning curve for me, but I am almost there. My final problem is getting the app to wait for the APIs to complete before moving the next Intent.

I have three calls each uploading data via my API. They are called from a button and only when the three are uploaded, should the button send the user to the next intent/screen.

My API calls are working and I can see the data in the database. However, since enqueue is asynchronous the calls are firing and the code is moving on the start the next intent before the data is present.

The code below is executed 3 times (once for each upload). I realise this is probably not the best way to do it, but I'm trying to get it working before I finesse the code. I thought that perhaps I could have a variable, UploadedReadCount, that I increment in the onResponse, but this doesn't seem to be working properly. Could someone offer some advice as to how I should be pausing the code until the APIs complete? For example, is there an enqueue methos that isn't async?

            ReadInterface.create().AddRead("new", rFuel, rRegister, rReadDate, rRead)
            .enqueue(object : Callback<UploadedRead> {

                override fun onFailure(call: Call<UploadedRead>, t: Throwable) {
                    Log.d("Err: ", t.localizedMessage!!)

                override fun onResponse(call: Call<UploadedRead>, response: Response<UploadedRead>) {
                    Log.d("Response: ", response.body().toString())
                    val p = response.body()?.APIResult!![0]

                    msgShow("Gas read " + rRead.toString() + " uploaded")

                    UploadedReadCount += 1

        while ( UploadedReadCount < 3) {
            Log.d("Waiting ", UploadedReadCount.toString() + " reads uploaded...")

        val intent = Intent(this, {
            putExtra("ReadDate", txtReadDate.text.toString())


Read more here:

Content Attribution

This content was originally published by Tim Foster at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: