Reputation: 4536
I am a beginner in Kotlin and trying to implement MVVM design pattern on android development. I have to implement a Recyclerview in a fragment. How we can set adapter with value to a recyclerview from the viewmodel class since the api call is observed within the viewmodel.
My fragment class is look like as below
class NotesFragment : Fragment() {
lateinit var binding:FragmentNotesBinding
lateinit var viewModel:NoteListViewModel
companion object {
fun newInstance(param1: String): NotesFragment {
val fragment = NotesFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater,R.layout.fragment_notes,container,false)
viewModel = NoteListViewModel(binding)
return binding.root
}
is it good practice that we passing the binding object to our viewmodel class and updating the viewModel object again from ViewModel class as below
private fun onSuccess(success: NoteResponse?) {
dataVisibility.value=View.VISIBLE
success.let {
noteAdapter= noteAdapter(documentResponse?.result,mContext)
binding.viewModel=this
}
}
Upvotes: 3
Views: 5405
Reputation: 1369
The core about MVVM is seperation of concerns. ViewModel should not hold any reference to the View(Activity/Fragment). LikeWise your Data/Repository layer should not hold ViewModel reference.
So to achieve data flow you can use either Reactive Observables(Rx)/ LiveData from android architecture components to pass back the data.
1) Create MutableLiveData in your Viewmodel.
2) Set the MutableLiveData with api response model.
3) Observe the MutableLiveData in your Fragment for the response data.
4) Use the data to set your adapter inside your fragment.
Please check ViewModel - Developer document to understand better.
Upvotes: 6