Hi, i'm making a class that check audio input leve...
# coroutines
j
Hi, i'm making a class that check audio input level in Android, for do that I must call one method each 100ms in a separate thread and notify the value with a lambda
block
, for the moment I have this (old school hava style) and I guess I can do better with coroutines.
mustStopThread
is a boolean that is false when class is created and true when I must stop the check (when I quit the activity). What I can do better ?
Copy code
init {
    Thread(Runnable {
        while (!mustStopThread) {
            val lastMaxSoundLevel: Int = mediaRecorder.maxAmplitude
            block.invoke(lastMaxSoundLevel)
            Thread.sleep(100)
        }
    }).start()
}
⏸️ 2
e
First, replace
mustStopThread
with a scope:
Copy code
val myScope = CoroutineScope(Dispatchers.Default)
Then, you can replace your code with:
Copy code
init { 
    myScope.launch { 
        while (isActive) {
             ... // as before
             delay(100) // instead of Thread.sleep
        }
    }
}
When you need to stop, you’d call
myScope.cancel()
1
j
Thanks for the answer !
isActive
is very useful 🙂
e
In this particular case you don’t have to do
while (isActive)
and
while (true)
would work just as well, becuase
delay
checks for it. But the code just looks better and more understandable this way, highlighting the fact that you are looping not forever, but until cancellation.
👍 3
j
Agree, code is more declarative with
while(isActive)
👌