[英]When to call livedata observer?
On a button click i have to get some value from API call and then launch one screen.单击按钮我必须从 API 调用中获取一些值,然后启动一个屏幕。 I have two options:我有两个选择:
So which approach I should follow?那么我应该遵循哪种方法?
Actually it's up to you.其实这取决于你。 But i always prefer to call it in Activity's onCreate() function, so activity only has 1 observer.但我总是更喜欢在 Activity 的 onCreate() function 中调用它,所以 Activity 只有 1 个观察者。 If you call it in button click, it will give you multiple observers as much as button clicking如果您在按钮单击中调用它,它将为您提供与单击按钮一样多的多个观察者
Here is some example:下面是一些例子:
class HomeProfileActivity: BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initObserver()
initView()
}
private fun initObserver() {
viewModel.profileWorkProccess.observe(this, {
swipeRefreshLayout.isRefreshing = it
})
viewModel.isLoadingJobs.observe(this, {
layoutProgressBarJobs.visibility = View.VISIBLE
recyclerViewJobs.visibility = View.GONE
dotsJobs.visibility = View.GONE
})
//other viewmodel observing ......
}
private fun initView() {
imageProfile.loadUrl(user.image, R.drawable.ic_user)
textName.text = identity.user?.fullName
textAddress.text = identity.user?.city
buttonGetData.setOnClickListener { viewModel.getData(this) }
}
}
If the button is placed on the Activity, and data is displayed in the Fragment, you need to store variable in Activity ViewModel and observe it in Fragment如果按钮放置在Activity上,并且数据显示在Fragment中,则需要在Activity ViewModel中存储变量,并在Fragment中观察
You only need to call observe one time when fragment is created.您只需要在创建片段时调用一次观察。
For example:例如:
class MyActivity : AppCompatActivity() {
val viewModel: MyActViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
myButton.setOnClickListener { view ->
viewModel.getData()
}
}
}
class MyActViewModel: ViewModel {
val data: LiveData<String> = MutableLiveData()
fun getData() {}
}
class MyFragment: Fragment {
val actViewModel: MyActViewModel by activityViewModels()
override fun onActivityCreated(...) {
....
actViewModel.data.observe(viewLifecycleOwner, Observer { data ->
...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.