How to use ViewModel in Android

 

Dependencies

dependencies {
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'

ViewModel class and LiveData

class PracticeProgressViewModel : ViewModel() {
    
    private val _text = MutableLiveData<String>().apply {
        value = ""
    }

    val text: MutableLiveData<String> = _text

    fun setText(value: String){
        _text.value = value
    }
}

Fragment

class PracticeProgressFragment : Fragment() {

    private val homeViewModel: PracticeProgressViewModel by activityViewModels()

Observer Pattern

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        homeViewModel.text.observe(viewLifecycleOwner, {
            textView.text = it
        })

Update the ViewModel

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val button = binding.button
        button.setOnClickListener(View.OnClickListener {
        
            val totalAmoint = practiceDao.getTotalAmount()
            homeViewModel.setText(totalAmoint.toString())
        })
    }