Search code examples
androidandroid-fragmentsandroid-viewmodel

ViewModel set data in Activity and use in Fragment


I am trying no implement ViewModel, plaese help me get my head around this. I wish to set data in the Activity and use it in Fragment

MainActivity:

class MainActivity : AppCompatActivity(),ListFragment.OnFragmentInteractionListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)


        var viewModel = ViewModelProvider.NewInstanceFactory().create(TapupuViewModel::class.java)
        viewModel.setData(movieList)
    }
    }

ViewModel:

class TapupuViewModel : ViewModel() {

    val message  = MutableLiveData<ArrayList<Movie>>()

    fun setData(msg:ArrayList<Movie>){
        message.setValue(msg)
    }
}

Fragment:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_list2, container, false)

        val model = ViewModelProvider(activity!!).get(TapupuViewModel::class.java)
        model.message.observe(viewLifecycleOwner, Observer {
            it?.let {
                moviesArrayList = it

            }
        })
        }

I am probably doing something wrong there. Can you please help me?


Solution

  • View <---> ViewModel <---> Repository <---> Room Dao

    The view is: Fragment/Activity

    No need to share any ViewModels or ... between your Activity and Fragments.

    class MyRepository {
        private val dao: YourDao = ...
    
        fun getModelFromLocal(): LiveData/RxJava/List<Model> = dao.getModel()
    }
    

    In your ViewModel

    private val repository: MyRepository  = ...
    val resultLiveData = MutableLiveData<SomeModelToShowOnUI>()
    
    fun onUISentEventToLoadData() {
        val data: SomeModelToShowOnUI = repository.getModelFromLocal()
        resultLiveData.value = data
    }
    

    Activity/Fragment observe changes from ViewModel:

    class MyFragment : Fragment() {
        override fun onViewCreated() {
            resultLiveData.observe(this, Observer {
                //update UI
            })
        }
    }
    

    Each Fragment/Activity has its own implementation.