I am trying to delay code in Kotlin I have tried
Thread.sleep(1000)
But its freezes the UI.
Does somebody know why this is happening And how to delay without freezing the UI?
What went wrong
Usage Thread.sleep(...)
Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
For the OP (Original Poster / Asker)'s clarification:
It freezes the UI, does somebody know why this is happening?
As mentioned above from the official documentation of Java, you are experiencing a some sort of freezing in the UI because you have called it in the Main Thread.
Main Thread or if you are doing your stuff in Android, it is often called the UI Thread:
On the Android platform, applications operate, by default, on one thread. This thread is called the UI thread. It is often called that because this single thread displays the user interface and listens for events that occur when the user interacts with the app.
Without using the help of multi-threading APIs (Such as Runnable
, Coroutines
, RxJava
), you will automatically be invoking Thread.sleep(1000)
on the UI Thread that is why you are experiencing such "UI Freezing" experience because, other UI Operations
are blocked from accessing the thread since you have invoke a suspension on it.
And how to delay without freezing the ui?
Harness the power of available APIs for multi-threading, so far it's good to start with the following options:
1. Runnable
In Java
// Import
import android.os.Handler;
// Use
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// do something after 1000ms
}
}, 1000);
In Kotlin
// Import
import android.os.Handler;
// Use
val handler = Handler()
handler.postDelayed({
// do something after 1000ms
}, 1000)
2. Kotlin Coroutines
// Import
import java.util.*
import kotlin.concurrent.schedule
// Use
Timer().schedule(1000){
// do something after 1 second
}
3. RxJava
// Import
import io.reactivex.Completable
import java.util.concurrent.TimeUnit
// Use
Completable
.timer(1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io()) // where the work should be done
.observeOn(AndroidSchedulers.mainThread()) // where the data stream should be delivered
.subscribe({
// do something after 1 second
}, {
// do something on error
})
Amongst the three, currently, RxJava is the way to go for multi threading and handling vast amount of data streams in your application. But, if you are just starting out, it is good to try out the fundamentals first.
References