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?
There is no direct way to achieve this in Kotlin, but we can use Java library functions in Kotlin for this purpose since Kotlin is based on Java. We will use the Timer() and schedule() functions to call a function after a delay.
Android App Development for Beginners sleep() in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
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
You can use Handler object https://developer.android.com/reference/android/os/Handler.
val handler = Handler()
val runnable = Runnable {
// code which will be delayed
}
handler.postDelayed(runnable, 1000)
1000 is time in miliseconds, you should replace it with your value.
If you don't want to freeze the UI, you need to execute your code off of the MainThread.
There are a lot of way of doing it. Some examples:
Thread {
Thread.sleep(1000)
// Your code
}.start()
You need https://github.com/ReactiveX/RxJava
Flowable.timer(1000, TimeUnit.MILLISECONDS)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe {
// Your code
}
GlobalScope.launch { // launch new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
reference: https://kotlinlang.org/docs/reference/coroutines-overview.html
GlobalSocpe.launch(Dispatchers.MAIN){
delay(5000)
}
this is the code part you asked for. But for your solution, first understand
launch
and
async
Similarly you should understand other values of
Dispatchers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With