Correctly implementing wait and notify in Kotlin

后端 未结 3 2001
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 11:54

According to this document, using wait and notify is discouraged in Kotlin: https://kotlinlang.org/docs/reference/java-interop.html

3条回答
  •  梦毁少年i
    2021-01-01 12:46

    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

提交回复
热议问题