'Collecting Flow<List> and displaying it in Compose (Kotlin)

Hello guys I have list of movies that I call from MovieApi.

In movieRepo I did this:

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)
            }
        }
      
        return popularMovies
    }

In MovieViewModel:

init{
     viewModelScope.launch {
         repository.getPopularMovies().collect(){
            Log.i("COLLECTED", "$it")
         }
     }
 }


private suspend fun getPopularMovies()  {
    
    return repository.getPopularMovies().collect()
}

I know that collect gets all Movies I want, but I need to display it in my HomeScreen with viewModel when I call getPopularMovies. I'm reading Flow docs but cant understan how this part works(news part is from Flow documentation):

newsRepository.favoriteLatestNews.collect { favoriteNews ->
               // Update View with the latest favorite news
            }


Sources

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

Source: Stack Overflow

Solution Source