Problem: sequential output when executing a function in kotlin

fun main () {
for (x1 in 1…10) {
println(x1)
Thread.sleep(1000) // wait for 1 second
}
}

the code will output the result “1, 2,…, 10” in 10 seconds.
I would like “1”, pause 1 second, “2”, pause 1 second …, “10”.
Help me

Please learn to properly format code and text, otherwise, it really hard to read. Your program should doe exactly what you want. If you are running it in https://play.kotlinlang.org/, it will dump the whole output in the end of evaluation due to specifics of its working model (it is not asynchronous).

1 Like

Thanks for the answer.
The code runs on an Android device.
Please how do I get the output in the process of executing the code?

unfortunately, I’m wasting my time but I can’t figure out a simple question. Help!
At least in what direction to move

fun main () {
for (x1 in 1…10) {
println(x1)
Thread.sleep(1000) // wait for 1 second
}
}

the code will output the result “1, 2,…, 10” in 10 seconds.
I would like “1”, pause 1 second, “2”, pause 1 second …, “10”.
The code runs on an Android device.

That might be due to how logcat works. The actual code should pause and everything, but logcat probably fetches the result after a few moments. Maybe try increasing the delay to 10 seconds? Or maybe using Log.d(x1) instead?

increasing the delay doesn’t help ((

Your code is already correct for what you want to achieve. But some environments unfortunately don’t print the output until the code terminates.

Like for example scratch files in intellij. They buffer the output as it happens and print it when the code terminates.

1 Like

so what should I do?

We cannot help you with the code, because it is correct already. But we might be able to help you with the environment. Please describe in more detail how you run the code and how and where you observe it’s output.

Thanks! The code is simplified, of course. Instead of the “println(x1)” command, another function. Created in Android Studio and executed on an Android phone

That’s not enough details.

What function are you using? If you are setting the text in a TextView, then the problem is that your code is executing on the UI thread, so every time you do Thread.sleep, you are literally stopping your program from running anything, and I mean anything, that is user-facing. When you set the text in a TextView, it doesn’t immediately draw to the screen, instead it saves that text internally until your app draws itself again, which can not happen if your UI thread is sleeping. My advice would be to instead use lifecycleScope.launch { ... } in your Activity and then inside of the launch block use delay(1000) instead of Thread.sleep(1000)

Here’s a runnable example of your code but modified so we can see the time (in milliseconds) of how long the thread slept:

fun main () {
    for (x1 in 1..3) {
        val timeStart = System.currentTimeMillis()
        println(x1)
        Thread.sleep(1000) // wait for 1 second
        println("Milliseconds slept: ${(System.currentTimeMillis() - timeStart)}")
    }
}

Try pressing the run button. It is waiting one second between each print.
The output could be delayed being visible for several reasons. Sometimes it’s as simple as flushing the output (e.x. System.out.flush().

Since you mention the problem is observing the output and that you are using some other code than printing to the stdout, it’s likely the other function is part of the issue.

1 Like

sorry. I only see one output after 3 seconds

Yes, the website buffers the output as well. But if you copy that code into an empty kotlin project (not anroid, just the normal jvm target) you will see the output appear 1 line at a time.

1 Like

May you please include what function you are using to print out the output? Because that function is probably causing the problem

Thanks for the answer. Yes, I use “TextView” and “setBackgroundResource” for images. But they are rewritten during the execution of the function. The problem, as I understand it, is output buffering on Android.

Unfortunately, my program is for Android…

It is not output buffering though. The problem is that when you do Thread.sleep, the whole app literally just stops, nothing gets redrawn. The app keeps stopping, then adding a number to the TextView, without redrawing anything, until your for loop is totally done. When your for loop is done, Android finally gets an opportunity to redraw your app, so it does so. The easiest way to fix this would be to follow the coroutine example that I replied with a couple of replies upwards.

The reason that my coroutine example works is that it uses delay instead of Thread.sleep. delay is a suspend function, which means that it stops the execution of the rest of the code temporarily and lets everything else run, including the redrawing of views. Thread.sleep, on the other hand, forces the whole thread to sleep, and because your code is running on the UI thread, redrawing just doesn’t happen.

2 Likes

Also see this for a more thorough explanation:

1 Like