How to step through suspend function calls when debugging Kotlin coroutines

This page shows some general techniques. In short, run with enabled assertions (-ea JVM flag). kotlinx-coroutines-debug module is specifically designed for what its name says. This is how I use it in unit tests; runBlocking { DebugProbes.install() val deferred = async { methodUnderTest() } delay(3000) DebugProbes.dumpCoroutines() println(“\nDumping only deferred”) DebugProbes.printJob(deferred) DebugProbes.uninstall() cleanup() } There’s a … Read more

Unit testing a Kotlin coroutine with delay

If you don’t want any delay, why don’t you simply resume the continuation in the schedule call?: class TestUiContext : CoroutineDispatcher(), Delay { override fun scheduleResumeAfterDelay(time: Long, unit: TimeUnit, continuation: CancellableContinuation<Unit>) { continuation.resume(Unit) } override fun dispatch(context: CoroutineContext, block: Runnable) { //CommonPool.dispatch(context, block) // dispatch on CommonPool block.run() // dispatch on calling thread } } … Read more

kotlin coroutines, what is the difference between coroutineScope and withContext

Formally, coroutineScope is a special case of withContext where you pass in the current context, avoiding any context switching. Schematically speaking, coroutineScope ≡ withContext(this.coroutineContext) Since switching contexts is just one of several features of withContext, this is a legitimate use case. withContext waits for all the coroutines you start within the block to complete. If … Read more

MutableStateFlow is not emitting values after 1st emit kotlin coroutine

Pankaj’s answer is correct, StateFlow won’t emit the same value twice. As the documentation suggests: Values in state flow are conflated using Any.equals comparison in a similar way to distinctUntilChanged operator. It is used to conflate incoming updates to value in MutableStateFlow and to suppress emission of the values to collectors when new value is … Read more

How to use code that relies on ThreadLocal with Kotlin coroutines

Coroutine’s analog to ThreadLocal is CoroutineContext. To interoperate with ThreadLocal-using libraries you need to implement a custom ContinuationInterceptor that supports framework-specific thread-locals. Here is an example. Let us assume that we use some framework that relies on a specific ThreadLocal to store some application-specific data (MyData in this example): val myThreadLocal = ThreadLocal<MyData>() To use … Read more

AsyncTask in Android with Kotlin

AsyncTask is an Android API, not a language feature that is provided by Java nor Kotlin. You can just use them like this if you want: class someTask() : AsyncTask<Void, Void, String>() { override fun doInBackground(vararg params: Void?): String? { // … } override fun onPreExecute() { super.onPreExecute() // … } override fun onPostExecute(result: String?) … Read more