Colton Idle
01/27/2023, 6:20 AMgetTeams()
and getPlayersFromTeamId(teamId)
So essentially, I want to flatten TeamsDTO and PlayerDTO into a "domain" Teams object which contains the list of Players inside of it.
data class Team(val name: String, val players: List<Player>)
Now I know I can probably get fancy with flows and stuff like that, but in terms of modelling the data, I think it kinda gets tricky because I'm using data classes and so I can't just update these things easily. I'll put my current impl in the thread, but appreciate any pointers. thanksColton Idle
01/27/2023, 6:26 AMfun createDomainTeamsObject() : List<Team>{
val finalList = mutableListOf<Team>()
val teams = api.getTeams()
teams.when{
Success -> {
teams.forEach { team ->
finalList.add(Team(team.name, players = null))
val players = api.getPlayersFromTeamId(team.id)
players.when {
Success -> {
//How should I now add Players to the team?
}
}
}
}
}
}
Zaki Shaikh
01/27/2023, 6:52 AMColton Idle
01/27/2023, 6:54 AMColton Idle
01/27/2023, 6:54 AMColton Idle
01/27/2023, 6:56 AMStephan Schröder
01/27/2023, 8:46 AM{teams/players}.when {
Success -> {
code is pseudo code isn't it? Or is when
a custom extension function? I'm trying to wrap my head around what's happening here.
My general advise is to use `map`/`mapNotNull.`
Let's assume api.getTeams()
returns a nullable list of TeamDTO
(it's null, if the request goes wrong) and api.getPlayersFromTeamId(team.id)
returns a nullable list of PlayerDTO
.
fun createDomainTeamsObject() : List<Team> =
api.getTeams()?.let { teamDTOs: List<TeamDTO> ->
teamDTOs.map { teamDTO ->
val playerDTOs: List<PlayerDTO> = api.getPlayersFromTeamId(teamDTO.id) ?: emptyList()
val players: List<Player> = playerDTOs.map { playerDTO ->
Player(...)
}
Team(teamDTO.name, players)
}
} ?: emptyList()
This code assumes you'll always get a valid Team/Player from a TeamDTO/PlayerDTO. If that's not the case because sometimes the dto might not have all the information required, use mapNotNull
instead.Colton Idle
01/27/2023, 4:19 PMColton Idle
01/27/2023, 5:15 PMFrancesc
01/28/2023, 12:20 AMColton Idle
01/28/2023, 6:28 AMFrancesc
01/28/2023, 11:06 PMResult
type of object)
data class TeamDto(
val id: Int,
val name: String,
)
data class PlayerDto(
val id: Int,
val name: String,
)
data class Player(
val id: Int,
val name: String,
)
data class Team(
val id: Int,
val name: String,
val players: List<Player>
)
interface RemoteDataSource {
suspend fun getTeams(): Response<List<TeamDto>>
suspend fun getPlayers(teamId: Int): Response<List<PlayerDto>>
}
class NetworkException : IOException()
fun <T> Response<T>.valueOrThrow():T = if (isSuccessful && body() != null) body()!! else throw NetworkException()
suspend fun getTeams(): List<Team> {
val teams = remoteDataSource.getTeams().valueOrThrow()
return teams.map { team ->
Team(
id = team.id,
name = team.name,
players = remoteDataSource.getPlayers(team.id).valueOrThrow().map { player ->
Player(
id = player.id,
name = player.name,
)
}
)
}
}