[英]Return query results to main thread without blocking
我在使用Kotlin協程時遇到麻煩,正在嘗試查詢數據庫並將結果返回到主線程,但是我不知道如何在不“凍結”主線程的情況下做到這一點。 在這種情況下,runBlocking將是罪魁禍首,但是我不確定該用什么代替它。 任何幫助都將不勝感激!
fun getResults() : List<String> {
val results = ArrayList<String>()
runBlocking {
viewModelScope.launch(Dispatchers.IO) {
openConnection()
try {
statement = connection!!.createStatement()
resultSet = statement!!.executeQuery("blah blah blah")
while (resultSet != null && resultSet!!.next()) {
results.add(resultSet!!.getString(1))
}
} catch (e: Exception) {
Log.d("getList Catch", e.toString())
}
closeConnection()
}.join()
}
return results
}
當與可暫停的協程或回調一起適當地確定阻塞任務的范圍時,不需要
runBlocking
。
如前所述,您有幾個選擇:
懸浮的協程
suspend fun getResults() : List<String> = suspendCancellableCoroutine { cont ->
openConnection()
val results = ArrayList<String>()
try {
statement = connection!!.createStatement()
resultSet = statement!!.executeQuery("blah blah blah")
while (resultSet != null && resultSet!!.next()) {
results.add(resultSet!!.getString(1))
}
closeConnection()
cont.resumeWith(Result.success(results))
} catch (e: Exception) {
Log.d("getList Catch", e.toString())
closeConnection()
cont.resumeWith(Result.failure(e))
}
}
匿名回調
fun getResults(cb: (List<String>) -> Unit) {
viewModelScope.launch(Dispatchers.IO) {
openConnection()
val results = ArrayList<String>()
try {
statement = connection!!.createStatement()
resultSet = statement!!.executeQuery("blah blah blah")
while (resultSet != null && resultSet!!.next()) {
results.add(resultSet!!.getString(1))
}
} catch (e: Exception) {
Log.d("getList Catch", e.toString())
}
cb.invoke(results)
closeConnection()
}
}
我個人的偏愛是第二種選擇,因為它消除了方法使用者必須了解和實現可掛起的需求。
launch(Dispatchers.IO) {
val results = getResults()
// handle results
}
與
getResults {
// handle results
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.