Android Kotlin Coroutines: what is the difference between flow, callbackFlow, channelFlow,… other flow constructors

For callbackFlow: You cannot use emit() as the simple Flow (because it’s a suspend function) inside a callback. Therefore the callbackFlow offers you a synchronized way to do it with the trySend() option. Example: fun observeData() = flow { myAwesomeInterface.addListener{ result -> emit(result) // NOT ALLOWED } } So, coroutines offer you the option of … Read more

How to emit Flow value from different function? Kotlin Coroutines

You can use StateFlow or SharedFlow APIs for such use case. Here’s a sample code with the usage of StateFlow. import kotlinx.coroutines.* import kotlinx.coroutines.flow.* val chatFlow = MutableStateFlow<String>(“”) fun main() = runBlocking { // Observe values val job = launch { chatFlow.collect { print(“$it “) } } // Change values arrayOf(“Hey”, “Hi”, “Hello”).forEach { delay(100) … Read more

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

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

Is Kotlin Flow’s Collect is only internal kotlinx.coroutines API?

The answer is, NO, collect is not only internal kotlinx.coroutines API. The error message is misleading. As per @ir42’s comment, add import kotlinx.coroutines.flow.collect solve the problem. Additional info, why I didn’t pick collectLatest as the answer collect and collectLatest is different. Using this example fun simple(): Flow<Int> = flow { // flow builder for (i … Read more

tech