0

I have a BaseFragment and BaseViewModel. I created HomeFragment that extended from BaseFragment. Now I observe a LiveData of BaseViewModel but observing data is not working.

// BaseFragment

abstract class BaseFragment<VDB: ViewDataBinding, VM: BaseViewModel>: Fragment() {
    lateinit var mBinding: VDB
    lateinit var mViewModel: VM
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val parameterizedType = javaClass.genericSuperclass as? ParameterizedType
    
        @Suppress("UNCHECKED_CAST")
        val vmClass = parameterizedType?.actualTypeArguments?.getOrNull(1) as? Class<VM>?
        if (vmClass != null) mViewModel = ViewModelProvider(this)[vmClass]
    }
    ......
}

//BaseViewModel

abstract class BaseViewModel(application: Application) : AndroidViewModel(application) {
    val isMeet = MutableLiveData(true)

    //.... code to change isMeet ....

//HomeFragment

class MainFragment: BaseFragment<FragmentMainBinding, MainViewModel>() {
    override fun onResume() {
        super.onResume()
        mViewModel.isMeet.observe(viewLifecycleOwner) {
            Log.d(TAG, "setupViews: a $it") // there isn't any happened
        }
        Log.d(TAG, "onResume: ")
    }
nauq
  • 1

1 Answers1

0

Could you please try this?

val isMeet = MutableLiveData<Boolean>().apply { value = true }
Enes Zor
  • 973
  • 8
  • 14
  • It is same as val isMeet = MutableLiveData(true) Still not working – nauq Oct 31 '22 at 08:43
  • The problem is in base fragment probably. Could you initialise your view model in child fragment and try it? It needs to be work. – Enes Zor Oct 31 '22 at 11:48
  • I tried it. Not working. It's too hard to understand. Observing data work only once time when starting fragment. After that, with any changes data of LiveData, no any thing happen in observer. – nauq Nov 01 '22 at 03:05
  • Are you working background thread? Could you share how you update live data in view model? – Enes Zor Nov 01 '22 at 06:30
  • I think I figured out the root cause. I updated isMeet from another instance of class that extends from BaseFragment ~~ – nauq Nov 10 '22 at 08:28