繁体   English   中英

为什么在 Kotlin 在 Android Studio 中使用 async{} 后,我得到 LiveData 的 null 值?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM