Mehrdad Dolatkhah
Mehrdad Dolatkhah

Reputation: 688

how to use the same mutableLiveData in ViewModel from fragment and dialog fragment

I have a ViewModel, that I used in Fragment and DialogFragment. In Dialog Fragment, I try to update MutableLiveData value in Dialog Fragment and then use that value from MutableLiveData in my Fragment. as I check In Dialog Fragment I have data inside MutableLiveData but when trying to access that data inside fragment I got null. may please guide me on how to fix this problem?

in ViewModel:

val width = MutableLiveData<String>()
val height = MutableLiveData<String>()
val length = MutableLiveData<String>()

in DialogFragment:

vModel.width.value = "6"
vModel.height.value = "6"
vModel.length.value = "6"

and in my fragment that when I try to access data from MutableLiveData:

println(vModel.width.value)
println(vModel.height.value)
println(vModel.length.value)

this is my BaseFragment:

abstract class BaseFragment<B : ViewDataBinding, V : BaseViewModel>(
    private val layout: Int,
    private val viewModel: V
) : Fragment() {

    private lateinit var v: View
    protected lateinit var binding: B
    protected lateinit var vModel: V


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        binding = DataBindingUtil.inflate(inflater, layout, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        this.vModel = viewModel


        initVariables()
        initObserves()
        initViews()

        return binding.root
    }

    abstract fun initVariables()
    abstract fun initObserves()
    abstract fun initViews()

}

this is my BaseDialogFragment:

abstract class BaseDialogFragment<B : ViewDataBinding, V : BaseViewModel>(
    private val layout: Int,
    private val viewModel: V
) : DialogFragment() {

    private lateinit var v: View
    protected lateinit var binding: B
    protected lateinit var vModel: V


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        binding = DataBindingUtil.inflate(inflater, layout, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        this.vModel = viewModel


        initVariables()
        initObserves()
        initViews()

        return binding.root
    }

    abstract fun initVariables()
    abstract fun initObserves()
    abstract fun initViews()

}

Upvotes: 2

Views: 769

Answers (1)

Sergey
Sergey

Reputation: 394

Make sure you load your ViewModel with activity context so one instance will be shared with all fragments, and not be recreated for each one

something like this

val viewModel by activityViewModels<MainViewModel> ()

Upvotes: 1

Related Questions