Search code examples
androidkotlinmvvmobserversandroid-viewmodel

How to pass data or add observer at onBackPressed event in FragmentActivity


I'm developing android app and I'm facing problem with passing data when user pressed back button (which means onBackPress event is fired). I wanted to fire event with observer with viewmodel but it doesn't work. like this.

// First Fragment
private val viewModel: MyViewModel by bindViewModel()
viewModel.currencyVal.observe { state ->
    Timber.i("Event fired")
}
    ...

// Second fragment which was displayed with fragment transaction. This code is when user pressed back button. like override fun onBackPressed
private val viewModel: MyViewModel by bindViewModel()
viewModel.currencyVal(5)

// MyViewModel
    ...
val currencyVal = MutableLiveData<Int>()
    ...
fun setCurrencyVal(currencyVal: Int) {
    currencyVal.value = currencyVal
}

Here's bindViewModel function

protected inline fun <reified T : ViewModel> bindViewModel(
    crossinline initializer: T.() -> Unit = {}
): Lazy<T> = nonConcurrentLazy {
    ViewModelProviders.of(requireActivity())
        .get(T::class.java)
        .also { it.initializer() }
}

And also passing data via fragment transaction doesn't work.

Could anyone please suggest how to pass data when user presses back button in FragmentActivity?

Thanks.


Solution

  • I am missing something. Is viewModel and firstViewModel the same object? Also if so are you sure that you are creating the ViewModel of the Activity, but not the Fragment?

     mViewModel = ViewModelProviders.of(requireActivity()).get(YourViewModel.class);