我正在使用 viewModel 从房间数据库中提取实时数据。我有 2 个从 viewModel 中提取的 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 …
Run Code Online (Sandbox Code Playgroud)