gpt4 book ai didi

android - 为什么在带有 Kotlin 的 Android Studio 中使用 async{} 后我得到 LiveData 的空值?

转载 作者:行者123 更新时间:2023-12-04 01:16:21 24 4
gpt4 key购买 nike

代码A查询LiveData<List<MVoice>>与房间并在 RecyclerView 中显示它们控制,效果很好。

我知道使用 Room 查询 LiveData 将在后台线程中运行,所以 val dd将在代码 B 中返回 null。

我认为val bb将返回正确的 List<MVoice>在代码 C 中,但实际上它返回 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() 不是挂起函数。因此,async { ... } 立即返回。

  • LiveData.getValue() 旨在获取其当前值,而无需等待下一个第一个值。这就是它不是挂起函数的原因。

关于android - 为什么在带有 Kotlin 的 Android Studio 中使用 async{} 后我得到 LiveData 的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63297352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com