简体   繁体   中英

When to call livedata observer?

On a button click i have to get some value from API call and then launch one screen. I have two options:

  1. Call the observer each time when user will click on button.
  2. Call the observer on fragment onActivityCreated() and store the value in variable and act accordingly on button click.

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. 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

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 ->
            ...
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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