Hi all, I'm trying to set up something like a Stat...
# coroutines
a
Hi all, I'm trying to set up something like a StateFlow (as this would be to drive an isLoading boolean for ui state) that would be set to true if there were active Jobs, and false if all jobs were completed. and you'd be able to add a job to it at any point to set it back to true. is it clear what I'm trying to do? I can begin to think of an ugly way of doing it but was wondering if anyone would have a clear solution
c
I don’t think there’s something built-in for that. But the best way I can think of doing this is tracking the launching and completion of each launched job and incrementing/decrementing a counter. Something like this should work:
Copy code
public class JobRunner(private val coroutineScope: CoroutineScope) {
    private val _count = MutableStateFlow(0)
    public val count get() = _count.asStateFlow()

    public fun launchInBackground(block: suspend () -> Unit) {
        val job = coroutineScope.launch {
            _count.update { it + 1 }
            block()
        }
        job.invokeOnCompletion {
            _count.update { it - 1 }
        }
    }
}
a
ooh yeah i was thinking of something along these lines, this is a really helpful starting point thanks