【发布时间】:2020-08-21 19:05:59
【问题描述】:
我正在使用 viewModel 从房间数据库中提取实时数据。我从我的 viewModel 中提取了 2 个 LiveData,然后我将运行一个函数从我的服务器中提取数据。在运行将从我的服务器获取信息的函数之前,我需要设置这两个值,因为这些值是帖子正文的一部分。
这是我的活动的一部分
var locationSeleted:Long=0L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView<ActivityBinding>(this,R.layout.activity)
//This is to get the viewmodel
val application = requireNotNull(this).application
val dataSource = Database.getInstance(application).DatabaseDao
val viewModelFactory = ViewModelFactory(dataSource, application)
val ViewModel = ViewModelProviders.of(this,viewModelFactory).get(ViewModel::class.java)
binding.ViewModel = ViewModel
binding.setLifecycleOwner (this)
//Get location from livedata
ViewModel.Location.observe(this, Observer {location ->
if (location == null){
//do something
}
else{
locationSeleted = location.locationId
}
})
//listens to the live data of the products value
ViewModel.Products.observe(this, Observer{products ->
if (products == null){
//do something
}
else{
myfunction(products)
}
})
这是我的视图模型的一部分
class ViewModel(val database: DatabaseDao, application: Application) : AndroidViewModel(application) {
//This gets the location selected
var Location: LiveData<LocationSelect> = database.get_location()
//This line gets the products
var Products: LiveData<Array<Products>> = database.get_products()
我当前的代码有效,但我可以想象,如果 Location LiveData 延迟,那么 myfunction 将在没有位置的情况下运行,并且 Post 调用将为 false。我的问题是当从 viewModel 设置位置和产品时如何调用 myfunction?或者有更好的方法吗?
谢谢你
【问题讨论】:
标签: android kotlin viewmodel android-livedata