'How to update the recyclerview when opening the app?

I'm looking for a list of movies in an API, the project is in MVVM and the search is being done perfectly. However, when opening the app, the user has to exit and open it again for the list to display the results. How to solve this?

In onStart I use Observe

   override fun onStart() {
    super.onStart()

    Log.d("TESTE", "onStart")
    viewModel.movieList.observe(this, Observer {
        Log.d("TAG", "onCreate: $it")
        for (i in it.results){
            list.add(i)
                }
        if (page < 66){
            page ++
        }

    })

In onResume

   override fun onResume() {
    super.onResume()
    val scope = MainScope()
    adapter.setDataSet(list)
    scope.launch {
        viewModel.getAllMovies(page)
        viewModel.getAllGenre()
    }


        val recyclerView : RecyclerView = findViewById(R.id.recycler_vie_movie_list)
        val layoutManager = GridLayoutManager(applicationContext, 3, GridLayoutManager.VERTICAL, false)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter


Solution 1:[1]

You are using activity callbacks incorrectly. White all of these code in onCreate (if you use Activity or use onViewCreated if it is Fragment).

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    viewModel.getMovieList() // realize this method in your ViewModel
    // and don't forget to set data to your movieList LiveData

    val recyclerView : RecyclerView = findViewById(R.id.recycler_vie_movie_list)
    val layoutManager = GridLayoutManager(applicationContext, 3, GridLayoutManager.VERTICAL, false)
    recyclerView.layoutManager = layoutManager
    recyclerView.adapter = adapter
    viewModel.movieList.observe(this, Observer { list->
        adapter.setDataSet(list)
    })

Inside the method setDataSet call notifyDataSetChanged()

Good luck in your endeavors!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nursultan Almakhanov