简体   繁体   中英

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 ?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM