Skip to content

Instantly share code, notes, and snippets.

@ChristopherME
Created May 6, 2021 18:19
Show Gist options
  • Save ChristopherME/2dced7b0970524a986b658f961d3a847 to your computer and use it in GitHub Desktop.
Save ChristopherME/2dced7b0970524a986b658f961d3a847 to your computer and use it in GitHub Desktop.
Fragment that shows a list of movies.
class MovieListFragment : Fragment(R.layout.fragment_movie_list) {
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
collectUiState()
}
private fun initView() {
binding.rvMovies.adapter = MovieListAdapter()
}
private fun collectUiState() {
viewLifecycleOwner.lifecycleScope.launch {
moviesViewModel.uiState.collect { state ->
renderUiState(state)
}
}
}
private fun renderUiState(state: MovieListUiState) {
with(state) {
// Progress
binding.progressBarMovies.isVisible = isLoading
// Bind movies.
(binding.rvMovies.adapter as MovieListAdapter)
.submitList(movies)
// Empty view
binding.tvMoviesEmpty.isVisible = !isLoading && movies.isEmpty()
// Display error if any. Only once.
error?.let {
it.consumeOnce { failure ->
Toast.makeText(
requireContext(),
"$failure",
Toast.LENGTH_LONG
).show()
}
}
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment