Jérôme Gully
03/18/2020, 11:22 AMblock
, 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 ?
init {
Thread(Runnable {
while (!mustStopThread) {
val lastMaxSoundLevel: Int = mediaRecorder.maxAmplitude
block.invoke(lastMaxSoundLevel)
Thread.sleep(100)
}
}).start()
}
elizarov
03/18/2020, 12:52 PMmustStopThread
with a scope:
val myScope = CoroutineScope(Dispatchers.Default)
Then, you can replace your code with:
init {
myScope.launch {
while (isActive) {
... // as before
delay(100) // instead of Thread.sleep
}
}
}
When you need to stop, you’d call myScope.cancel()
Jérôme Gully
03/18/2020, 1:51 PMisActive
is very useful 🙂elizarov
03/18/2020, 1:53 PMwhile (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.Jérôme Gully
03/18/2020, 2:04 PMwhile(isActive)
👌