Avatar ·

How to call a function with a delay in Kotlin?

Hello everyone! I'm a beginner in Kotlin and Android development. I have a simple scenario: after clicking a button, I need to wait 2 seconds and then perform some action (e.g., show a Toast or change text on the screen). I tried using Thread.sleep(), but it freezes the entire UI, and the app stops responding to touches. Here's my code:\n\n```kotlin\nbutton.setOnClickListener {\n Thread.sleep(2000) // App freezes!\n textView.text = "2 seconds passed"\n}\n```\n\nI understand this is wrong because I'm blocking the main thread (UI thread). But how to do this correctly in Kotlin? I've heard about coroutines, Handler, and timers, but I don't understand which approach is best for a simple delay. I need a solution that works on Android and doesn't require third-party libraries.