0

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
ldPr
  • 51
  • 5
  • 1
    You can add a [swiperefreshlayout](https://www.journaldev.com/10708/android-swiperefreshlayout-pull-swipe-refresh#:~:text=Android%20SwipeRefreshLayout%20is%20a%20ViewGroup,in%20the%20Facebook%20Newsfeed%20screen.) To update the recyclerview on swipe down – DenisMicheal.k May 13 '22 at 13:29
  • If your project is `MVVM`, why are you manipulating the data in a Fragment/Activity's `onStart` method? Anyhow, you could trigger a refresh when the app comes back from background by [detecting this](https://stackoverflow.com/questions/4414171/how-to-detect-when-an-android-app-goes-to-the-background-and-come-back-to-the-fo/19920353#19920353). – Martin Marconcini May 13 '22 at 13:37
  • In onResume I also implemented it but it didn't solve – ldPr May 13 '22 at 13:46

1 Answers1

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!