According to this document, using wait and notify is discouraged in Kotlin: https://kotlinlang.org/docs/reference/java-interop.html
You could use the kotlin Semaphore to suspend the coroutine instead of blocking a thread:
val semaphore = Semaphore(1, 0)
suspend fun runFetchLoop() = withContext(Dispatchers.Default){
while (isActive) {
val data = fetchData()
processData(data)
semaphore.acquire()
if (data.isEmpty()) {
semaphore.acquire()
}
semaphore.release()
}
}
fun notifyDataAvailable() = semaphore.release()
Here is a running example: https://pl.kotl.in/bnKeOspfs .
However I would prefer a cold Flow or a hot Channel to solve this problem. Here is a good article about cold flows and hot channels of the great Roman Elizarov