[英]Why do I get null value of LiveData after I have used async{} in Android Studio with Kotlin?
代碼 A 用 Room 查詢LiveData<List<MVoice>>
並將它們顯示在RecyclerView
控件中,效果很好。
我知道使用 Room 查詢 LiveData 將在后台線程中運行,因此val dd
將在代碼 B 中返回 null。
我認為val bb
會在代碼 C 中返回正確的List<MVoice>
,但實際上它返回的是 null,為什么?
代碼 A
binding.button.setOnClickListener {
mHomeViewModel.listVoice().observe(viewLifecycleOwner){ listMVoice->
adapter.submitList(listMVoice)
}
}
@Dao
interface DBVoiceDao{
@Query("SELECT * FROM voice_table ORDER BY createdDate desc")
fun listVoice():LiveData<List<MVoice>>
}
class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
fun listVoice()= mDBVoiceDao.listVoice()
}
class HomeViewModel(private val mDBVoiceRepository: DBVoiceRepository) : ViewModel() {
fun listVoice()= mDBVoiceRepository.listVoice()
}
代碼 B
binding.button.setOnClickListener {
val dd=mHomeViewModel.listVoice().value //It return null
}
... //It's the same as Code A
代碼 C
binding.button.setOnClickListener {
lifecycleScope.launch{
val aa=async { mHomeViewModel.listVoice() }
val bb=aa.await().value //It return null too
}
}
... //It's the same as Code A
您的代碼實際上可以通過刪除async-await
來簡化,並且它的工作方式相同。
binding.button.setOnClickListener {
val aa = mHomeViewModel.listVoice().value // It will be null too.
}
async {... }
中的代碼可能不是您認為的工作方式。 解釋這一點;
LiveData.getValue()
不是暫停 function 。 因此, async {... }
立即返回。
LiveData.getValue()
旨在獲取其當前值而不等待下一個第一個值。 這就是為什么它不是暫停 function 的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.