Equlo
Equlo

Reputation: 197

Kotlin coroutines flow collecting

I need to collect movies properly:

MovieRepo:

override suspend fun getPopularMovies() : Flow<List<Movie>>{
        val popularMovies : Flow<List<Movie>> = flow{
            while(true){
                val lastMovie = movieApi.getPopularMovies()
                Log.i("EMIT", "${emit(lastMovie)}")
                kotlinx.coroutines.delay(5000)
            }
        }

MovieViewModel:

      var popularMovies: MutableList<Movie> = mutableListOf()

init{
        viewModelScope.launch(Dispatchers.Default) {
            repository.getPopularMovies().collect{
               // popularMovies = mutableListOf()
                popularMovies.addAll(it)
            }
        }
    }

  @JvmName("getPopularMovies1")
  fun getPopularMovies(): MutableList<Movie> {
    return popularMovies
}

And HomeScreen:

  val viewModel = getViewModel<HomeViewModel>()

     var popularMovies = viewModel.getPopularMovies()

Later I send popularMovies to mutable list so I can click on it and see details also to check or uncheck favorite movie. Problem with this code that is collecting more movies after 5 secs of delay (first I have 3 movies it is ok, but later I have 6 then 9 etc.). HomeScreen is Composable function. Should I call movieViewModel in activity ?

Upvotes: 1

Views: 716

Answers (1)

Simon
Simon

Reputation: 1737

If you are expecting different movies from movieApi.getPopularMovies() over longer time period, you should change MutableList<Movie> to MutableSet<Movie> in order to remove duplicates automatically. This way new movies will be added only if api returns different list after delay(5000).

If you are using Jetpack compose, I'd suggest to use MutableState (read more about it here: https://developer.android.com/jetpack/compose/state)

Upvotes: 1

Related Questions