Created
March 8, 2021 17:59
-
-
Save lammertw/34b8059041705263bf0d13df1cb955a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RestaurantDetailViewModelImpl(api: Api, restaurantId: Int): RestaurantDetailViewModel { | |
private val _restaurant = api.restaurant(restaurantId) | |
private val _reservations = api.restaurantReservations(restaurantId) | |
private val _output = combine(_restaurant, _reservations) { restaurantResponse, reservationsResponse -> | |
// for simplicity we ignore error handling and exclude specific loading state for when the restaurant is loading | |
RestaurantDetailViewModel.Output( | |
name = (restaurantResponse as? Response.Success)?.data?.name ?: "Loading or error...", | |
priceCategory = (restaurantResponse as? Response.Success)?.data?.priceCategory ?: "Loading or error...", | |
reservations = when(reservationsResponse) { | |
is Response.Loading -> RestaurantDetailViewModel.Output.Reservations.Loading | |
is Response.Failed -> RestaurantDetailViewModel.Output.Reservations.NoReservations("Failed") | |
is Response.Success -> { | |
val reservations = reservationsResponse.data | |
if (reservations.isEmpty()) { | |
RestaurantDetailViewModel.Output.Reservations.NoReservations("No reservations yet") | |
} else { | |
RestaurantDetailViewModel.Output.Reservations.ReservationList(reservations.map { | |
RestaurantDetailViewModel.Output.Reservations.ReservationList.Reservation( | |
id = it.id, | |
date = "epoch: ${it.date}", // normally would do some formatting | |
numberOfGuests = it.numberOfGuests | |
) | |
}) | |
} | |
} | |
} | |
) | |
} | |
override val output = _output.distinctUntilChanged().wrap() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment