Member-only story
Build Stunning Grids in Minutes with LazyVerticalGrid | ๐ ๐ ๐ ๐ |

LazyVerticalGrid
in action in the NHL Hockey app on Google Play.Want to create stunning grid layouts in your Jetpack Compose app? Look no further than LazyVerticalGrid
. This powerful tool simplifies the process of designing and implementing efficient grid-based interfaces. In this comprehensive tutorial, Iโll share my insights and experience using LazyVerticalGrid
in a real-world production app on Google Play. Iโll explore its key features, best practices, and practical tips to help you create stunning grids that captivate your users. ๐ค
To populate the grid with player data, I make a network call to retrieve information for the selected season. Hereโs how I have implemented that:
// Wrapper for state management
sealed class PlayersUiState {
data object Loading : PlayersUiState()
data class Success(val players: List<Player>) : PlayersUiState()
data class Error(val throwable: Throwable) : PlayersUiState()
}
private val _uiState = MutableStateFlow<PlayersUiState>(PlayersUiState.Loading)
val uiState: StateFlow<PlayersUiState> = _uiState.asStateFlow()
private val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
viewModelScope.launch {
_uiState.emit(PlayersUiState.Error(throwable = throwable))
}
}
suspend fun getSkatersAndGoalies(season: String) {
viewModelScope.launch(context = ioDispatcher + coroutineExceptionHandler) {
repository.getAllNhlPlayers(season)
.catch { e ->
_uiState.emit(PlayersUiState.Error(Throwable(e.message ?: "Unknown error")))
}
.collectLatest { players ->
val sortedPlayers = (players.forwards + players.defensemen + players.goalies).sortedBy { it.lastName.default }
_uiState.emit(PlayersUiState.Success(sortedPlayers))
}
}
}
- Fetch player data: Use
repository.getAllNhlPlayers(season)
to retrieve player data for the specified season. - Handle errors: Catch any exceptions that might occur during the network call and emit an error state to the UI.
- Sort players: Combine the forwards, defensemen, and goalies, then sort them by last name.
- Emit success: Emit a success state to the UI, including the sorted players and the transformed season string.