Search code examples
androidmultithreadingkotlinkotlin-coroutineskotlin-stateflow

How many Stateflows can I observe at one time?


I develop apps for Android. I was wondering how many Kotlin Stateflows can I observe at one time? Every observe that I do is done on different CoroutineScope created by myself, dispatched by IO dispatcher or provided by lifecycle components of Android frameworks.

I have done various operations such as simple additions in infinite loop inside coroutines and using Android Studio profiler I have observed that launching a lot of coroutines that perform calculations causes high load on CPU.

Having in mind that Stateflow never completes, every collect on it is blocking and done on different CoroutineScope as examples and docs says, what is maximum amount of Stateflows that I can observe at one time without bothering that I will highly use CPU, create too many threads or just simply run out of device resources?


Solution

  • Subscriptions are still coroutines, and coroutines are cheap. There's definitely no universal bound we could tell you.

    every collect on it is blocking

    It suspends, it doesn't block. And you can always use takeWhile or the like to only collect from it until you can stop, or you can cancel the coroutine that's doing the collection (e.g. with withTimeout).

    The main constraint on performance is that updating a MutableStateFlow takes time linear in the number of subscribers to that StateFlow, so if you update a StateFlow with a thousand subscribers, it'll take ~a thousand times longer than updating a MutableStateFlow with only a single subscriber.