小编Max*_*Max的帖子

Kotlin - 在运行函数之前等待多个 LiveData 被观察到

我正在使用 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)

android viewmodel kotlin android-livedata

5
推荐指数
1
解决办法
2539
查看次数

标签 统计

android ×1

android-livedata ×1

kotlin ×1

viewmodel ×1