[英]How to wait till observe returns results in android kotlin?
我有這個 function,其中它要求觀察以檢查表中是否有數據,如果有則返回它們。 根據結果,我采用最新值並執行函數。
代碼片段
runBlocking {
val job = lifecycleScope.launch {
withContext(Dispatchers.Main) {
//1. first i need to wait here till observe returns results
viewModel.getAllRatings(context).observe(viewLifecycleOwner) { items ->
if (items.isNotEmpty()) {
rateVal = items[0].rateValue!!
}
}
}
}
job.join()
//2. then only after first step done i need this to execute.
if (rateVal > 0) {
ratingBar!!.rating = rateVal.toFloat()
}
}
getAllRatings()
fun getAllRatings(context: Context): LiveData<List<Rating>> {
val dpDatabase = DPDatabase.getDPDatabase(context = context.applicationContext)
feedbackSelectionRepository = FeedbackSelectionRepository(
dpDatabase
)
allRating = feedbackSelectionRepository.allRatings
return allRating
}
但是在當前代碼中。 第二個 function (2.) 甚至在第一部分 (1.) 獲得一些結果之前就已執行。
在調試器中,流程到達 1。然后無需等待就轉到 2。然后一些結果來自 1。
我只需要等待觀察結果。 我怎樣才能做到這一點? 請在這件事上給予我幫助
將 2 的代碼放入您在觀察回調中所做的事情中。 然后它會在觀察之后發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.