KOTLIN / CATATAN</>↗Kotlin03 Jul 2026
Kotlin coroutine lifecycle: the mental model A Kotlin coroutine is a lightweight concurrent task that runs inside a CoroutineScope and is controlled by a Job. The lifecycle is mostly about the state of that Job. At a high level: New → Active → Completing → Completed ↘ Cancelling → Cancelled Most of the time, you […]
KOTLIN / CATATAN</>↗Kotlin03 Jul 2026
In Kotlin, you cancel a coroutine safely by calling cancel() on its Job or scope, and making sure the coroutine code is cooperative: it should suspend regularly or check for cancellation. Basic example import kotlinx.coroutines.* fun main() = runBlocking { val job = launch { try { repeat(1_000) { i -> println("Working $i") delay(500) // […]
KOTLIN / CATATAN</>↗Kotlin03 Jul 2026
In Kotlin, use async to start concurrent work inside a coroutine scope, then call await() to get each result. Basic example: import kotlinx.coroutines.* suspend fun fetchUser(): String { delay(1000) return "User" } suspend fun fetchPosts(): List<String> { delay(1000) return listOf("Post 1", "Post 2") } fun main() = runBlocking { val userDeferred = async { fetchUser() […]
KOTLIN / CATATAN</>↗Kotlin03 Jul 2026
In Kotlin, a suspend function is declared with the suspend modifier. suspend fun fetchUser(): User { // Can call other suspend functions here return api.getUser() } A suspend function can pause without blocking the thread and later resume. It is commonly used with coroutines for asynchronous work. Example: import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking suspend fun greetAfterDelay() […]
KOTLIN / CATATAN</>↗Kotlin03 Jul 2026
Use kotlinx.coroutines.delay(…) inside a coroutine instead of Thread.sleep(…). Thread.sleep blocks the current thread. delay suspends the coroutine without blocking the thread, so other coroutines can keep running. import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking fun main() = runBlocking { println("Before delay") delay(1_000) // suspends for 1 second, does not block the thread println("After delay") } If you currently […]
KOTLIN / CATATAN</>↗Kotlin03 Jul 2026
In Kotlin, you can use runBlocking to start a coroutine scope that blocks the current thread until its coroutines finish, and launch to start a new coroutine inside that scope. import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking fun main() = runBlocking { launch { println("Coroutine is running") } println("Main coroutine continues") } Output may look like: Main coroutine […]