# coroutines

Sergio C.

12/03/2023, 3:30 PM
Hi, I'm having some strange unexpected behaviour with coroutines. This
function is called from compose and with each button click the id is increased, and the loop needs to run alone, no other loops should run at the same time. I would expect the while loop to stop when vmJob?.cancel is called, but if I click many times, and it doesn't need to be very fast, I can see multiple id in the logcat meaning that multiple loops are running at the same time. Ok I've tried cancelAndJoin, Mutexes, Semaphores, AtomicBooleans, ensureActive, hashmaps to store the jobs, and I still can run multiple while loops at once! What a heck is going on? 🤷
Copy code
var vmJob: Job? = null

override fun coroutineTest(id: Int) {
    vmJob = viewModelScope.launch(Dispatchers.IO) {
        while (isActive) {
            println("coroutineTest: $id")
solved 1

asdf asdf

12/03/2023, 4:57 PM
Have you tried using
instead of

Sergio C.

12/03/2023, 4:59 PM
yes. I tried everything and I've just found out it was an issue with the coroutine scope. The viewModel should have been recreated from the composable function and the scope should have been different.
I thought I was using the same viewModelScope but I was not. 😵
👀 1