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

How to call suspend function from Service Android?

You can create your own CoroutineScope with a SupervisorJob that you can cancel in the onDestroy() method. The coroutines created with this scope will live as long as your Service is being used. Once onDestroy() of your service is called, all coroutines started with this scope will be cancelled. class YourService : Service() { private … Read more

When to use Kotlin suspend keyword?

As a general rule of thumb, you should only declare your function suspend if the compiler forces you to. One possible exception to this rule would be if you’re defining this function as an open method (for instance in an interface) and you expect that some implementations/overrides will need to call suspending functions themselves. It’s … Read more

tech