如何使用转换为LiveData对象设置多个属性?

时间:2019-07-17 09:37:56

标签: android kotlin android-livedata

我有以下类型:

data class Match(
    @PrimaryKey var uid: Long? = null,
    @ColumnInfo var homeTeamId: Long? = null,
    @ColumnInfo var awayTeamId: Long? = null,
    @Ignore var homeTeam: Team? = null,
    @Ignore var awayTeam: Team? = null
)

data class Team(
    @PrimaryKey var uid: Long? = null,
    @ColumnInfo var captainId: Long? = null,
    @Ignore var captain: Player? = null
)

data class Player(
    @PrimaryKey var uid: Long? = null,
    @ColumnInfo var name: String? = null,
    var number: Int? = null
)

我正在以LiveData的身份获得比赛:

// inside fragment
matchDao.getLive(matchId).observe(this, Observer {})

我想使用homeTeamId属性在比赛中设置homeTeam。如何使用转换设置homeTeam,awayTeam和队长的值?

这是我所走的路:

fun getMatchLive(id: Long): LiveData<Match> {
    return Transformations.switchMap(matchDao.getLive(id)) { inputMatch ->
        val output1: LiveData<Match>? = inputMatch.homeTeamId?.run {
            Transformations.switchMap(teamDao.getLive(this)) { team ->
                team.captainId?.run {
                    Transformations.map(playerDao.getLive(this)) { player ->
                        team.apply {
                            captain = player
                            inputMatch.homeTeam = team
                        }
                        inputMatch
                    }
                }
            }
        }

        output1?.run {
            Transformations.switchMap(this) { inputMatch1 ->
                inputMatch1.awayTeamId?.run {
                    Transformations.switchMap(teamDao.getLive(this)) { team ->
                        team.captainId?.run {
                            Transformations.map(playerDao.getLive(this)) { player ->
                                team.apply {
                                    captain = player
                                    inputMatch1.awayTeam = team
                                }
                                inputMatch1
                            }
                        }
                    }
                }
            }
        }
    }
}

但是我几乎可以肯定,这既不是正确的方法,也不是可维护的。例如,如果要向match变量添加新属性,则必须转换output1.run的结果。

0 个答案:

没有答案