kotlin-coroutines
What is the hot flow and cold flow in coroutines and the difference between them?
A cold stream does not start producing values until one starts to collect them. A hot stream on the other hand starts producing values immediately. I would recommend to read below to understand hot and cold steams with usage: https://balwindersinghrajput.medium.com/complete-guide-to-livedata-and-flow-answering-why-where-when-and-which-6b31496ba7f3 https://developer.android.com/kotlin/flow/stateflow-and-sharedflow
When to use collect and collectLatest operator to collect kotlin flow?
Collect will collect every value , and CollectLatest will stop current work to collect latest value, The crucial difference from collect is that when the original flow emits a new value then the action block for the previous value is cancelled. flow { emit(1) delay(50) emit(2) }.collect { value -> println(“Collecting $value”) delay(100) // Emulate … Read more
Kotlin Flow vs LiveData
Flow is sort of a reactive stream ( like rxjava ). There are a bunch of different operators like .map, buffer() ( anyway less no. Of operator compared to rxJava ). So, one of the main difference between LiveData and Flow is that u can subscribe the map computation / transformation in some other thread … Read more
Unit test the new Kotlin coroutine StateFlow
It seems that the Android team changed the API and documentation after this thread. You can check it here: Continuous collection SharedFlow/StateFlow is a hot flow, and, as described in the docs, A shared flow is called hot because its active instance exists independently of the presence of collectors. It means the scope that launches … Read more
Difference between Job and Deferred in Coroutines Kotlin
So job is sort of an object that represents a coroutine’s execution and is related to structured concurrency, e.g. you can cancel a job, and all the children of this job will be also cancelled. From docs: Job is a cancellable thing with a life-cycle that culminates in its completion. Deferred is some kind of … Read more
Getting “Suspension functions can be called only within coroutine body” when calling withContext(Dispatchers.Main) inside a lambda
You can rewrite your bar function like this: fun bar(completion: () -> Unit) { GlobalScope.launch(Dispatchers.IO) { suspendCoroutine<Unit> { val lambda = { it.resume(Unit) } foo(lambda) } withContext(Dispatchers.Main) { completion() } } }
When using kotlin coroutines, how do I unit test a function that calls a suspend function?
Fixing async As implemented, your someFun() will just “fire and forget” the async result. As a result, runBlocking does not make a difference in that test. If possible, make someFun() return async‘s Deferred and then, in runBlocking, call await on it. fun someFun(): Deferred<Unit> { // … Some synchronous code return async { suspendFun() } … Read more