Kotlin coroutines: why can't I see logs until the end?

Viewed 989

I'm new with kotlin coroutines and have some doubts. So I'm trying to download a list of fonts using a kotlin coroutine, and I added some logs to see when a font is downloaded, or a message when it already existed. I was expecting to see one log each time a font is accessed, however I see only the progressBar, and when it gets hidden, I see all the logs at once. Am I doing something wrong?

private fun init() {
    val job = Job()
    val bgScope = CoroutineScope(Dispatchers.IO + job)

    bgScope.launch {
        getStuff()
    }
}

fun getStuff() {
    val uiScope = CoroutineScope(Dispatchers.Main + Job())
    uiScope.launch {
        progressbar.visibility = View.VISIBLE
    }

    for (font in jsonObject.fontList) {
        if (!font.exists()) {
            downloadFile(font)
            Timber.d("file " + font.id + " downloaded: " + font.exists())
        } else {
            Timber.d("file " + font.id + " already exists ")
        }

    }

    uiScope.launch {
        progressbar.visibility = View.GONE
    }
1 Answers

That's because your

for (font in jsonObject.fontList) {
        if (!font.exists()) {
            downloadFile(font)
            Timber.d("file " + font.id + " downloaded: " + font.exists())
        } else {
            Timber.d("file " + font.id + " already exists ")
        }

    }

runs in another thread, and delays the response.Therefore, you should modify you progress visibility after the downloadFile has finished.

You should start the coroutine inside your downloadFileMethod() along with the progress bar switching on/off.

Related