Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to delay code in Android without making the UI freeze

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?

like image 299
asaf Avatar asked Jan 24 '19 14:01

asaf


People also ask

How do I add a delay on Kotlin?

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.

How do I put Android studio to sleep?

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.


4 Answers

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

  • https://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
  • https://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-1-of-5/
  • https://github.com/ReactiveX/RxJava
  • https://github.com/Kotlin/kotlinx.coroutines
like image 167
Joshua de Guzman Avatar answered Oct 06 '22 12:10

Joshua de Guzman


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.

like image 34
DawidJ Avatar answered Oct 06 '22 11:10

DawidJ


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 {
    Thread.sleep(1000)
    // Your code
}.start()

Rx

You need https://github.com/ReactiveX/RxJava

Flowable.timer(1000, TimeUnit.MILLISECONDS)
    .subscribeOn(AndroidSchedulers.mainThread())
    .subscribe { 
        // Your code
    }

Kotlin coroutine

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

Documentations:

  • https://developer.android.com/guide/components/processes-and-threads
  • https://developer.android.com/topic/performance/threads
  • https://developer.android.com/training/multiple-threads/communicate-ui
like image 6
Kevin Robatel Avatar answered Oct 06 '22 10:10

Kevin Robatel


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

like image 2
A_rmas Avatar answered Oct 06 '22 12:10

A_rmas