简体   繁体   English

在设置观察块内的变量值后获取 null 值

[英]Getting null value after setting the value of a variable inside observe block

In my UI - MainActivity.kt在我的用户界面中 - MainActivity.kt

I have:我有:

private var recommendationCount: Int? = null

onCreate{
   
   viewmodel.recommended.observe(this){
      recommendationCount = it.size
   }
   
   //I need to set the view outside the observe
   binding.myTextView.text = recommendationCount.toString()
   
   //it returns null
  
}

When I set my textview outside the observe block, it returns a null value.当我在观察块之外设置我的 textview 时,它返回一个 null 值。 but when I set it inside, it returns the correct value.但是当我在里面设置它时,它会返回正确的值。

I need to set it outside.我需要把它放在外面。

You cannot set it outside the observer simply because the onCreate() executes all the code inside it before the viewModel changes the value of the Observable(Live data, I guess) that you are observing in onCreate() As a solution, you can give your variable a default value which will be changed in the observer block when the viewModel changes the value of the Observable(Live data, I guess)您不能仅仅因为 onCreate() 会在 viewModel 更改您在 onCreate() 中观察到的 Observable(我猜是实时数据)的值之前执行其中的所有代码作为解决方案,所以您不能将其设置在观察者之外作为解决方案,您可以给出您的变量是一个默认值,当 viewModel 更改 Observable 的值时,它将在观察者块中更改(我猜是实时数据)

Since you want to merge the values from multiple LiveData, you need to combine them into a single LiveData.由于要合并来自多个 LiveData 的值,因此需要将它们组合成一个 LiveData。 You can't just grab data from each of them sequentially, because LiveData is not intended to work synchronously (you can use the value property, but this is not robust because it's possible to check the value before its initial value is set).您不能只按顺序从每个数据中获取数据,因为 LiveData 并非旨在同步工作(您可以使用value属性,但这并不可靠,因为可以在设置初始值之前检查该值)。

You need to combine them into a single LiveData or Flow by merging them.您需要通过合并将它们组合成一个 LiveData 或 Flow。 It can be done with LiveData using MediatorLiveData, but it's easier with Flows because you can use the combine function.它可以通过使用 MediatorLiveData 的 LiveData 完成,但使用 Flows 更容易,因为您可以使用combine function。 You could do something like this, converting flows and back to LiveData to avoid having to use coroutines:你可以做这样的事情,将流转换回 LiveData 以避免使用协程:

val combinedLiveData = combine(
        liveDataA.asFlow(), 
        liveDataB.asFlow(), 
        liveDataC.asFlow()
    ) { a, b, c -> 
        a + b + c 
    }.asLiveData()

But if you are using coroutines, you wouldn't need to convert back to LiveData.但如果您使用协程,则无需转换回 LiveData。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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