如何使用Room将嵌套数据传递到ViewModel层?

时间:2019-08-10 04:15:14

标签: android kotlin android-room

我刚开始使用Room,并且正在使用它来保持DarkSky API的天气响应。响应对象如下所示:

data class WeatherResponse(
        val currently: Currently,
        val daily: Daily,
        val flags: Flags,
        val hourly: Hourly,
        val latitude: Double,
        val longitude: Double,
        val minutely: Minutely,
        val offset: Double,
        val timezone: String
)

我已经能够使用“当前”实体成功地将“当前”数据传递到ViewModel并在屏幕上显示:

const val CURRENT_WEATHER_ID = 0

@Entity(tableName = "current_weather")
data class Currently(
        @ColumnInfo(name = "apparentTemperature")
        val apparentTemperature: Double,
        @ColumnInfo(name = "cloudCover")
        val cloudCover: Double,
        @ColumnInfo(name = "dewPoint")
        val dewPoint: Double,
        @ColumnInfo(name = "humidity")
        val humidity: Double,
        @ColumnInfo(name = "icon")
        val icon: String,
        @ColumnInfo(name = "nearestStormBearing")
        val nearestStormBearing: Int,
        @ColumnInfo(name = "nearestStormDistance")
        val nearestStormDistance: Int,
        @ColumnInfo(name = "ozone")
        val ozone: Double,
        @ColumnInfo(name = "precipIntensity")
        val precipIntensity: Int,
        @ColumnInfo(name = "precipProbability")
        val precipProbability: Int,
        @ColumnInfo(name = "pressure")
        val pressure: Double,
        @ColumnInfo(name = "summary")
        val summary: String,
        @ColumnInfo(name = "temperature")
        val temperature: Double,
        @ColumnInfo(name = "time")
        val time: Long,
        @ColumnInfo(name = "uvIndex")
        val uvIndex: Int,
        @ColumnInfo(name = "visibility")
        val visibility: Double,
        @ColumnInfo(name = "windBearing")
        val windBearing: Int,
        @ColumnInfo(name = "windGust")
        val windGust: Double,
        @ColumnInfo(name = "windSpeed")
        val windSpeed: Double
) {
    @PrimaryKey(autoGenerate = false)
    var id: Int = CURRENT_WEATHER_ID
}

和当前CurrentDao:

@Dao
interface CurrentWeatherDao {

    // UPdate or inSERT.  There can only ever be one Currently weather object in the db
    // so if it doesn't exist, insert it, and if it does, update it.
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun upsert(weatherEntry : Currently)

    // select everything from the table where the ID matches CURRENT_WEATHER_ID
    // This should only ever be one thing, since there's only one Currently in the table
    @Query("select * from current_weather where id = $CURRENT_WEATHER_ID")
    fun getWeather() : LiveData<Currently>
}

我认为这可以应用于响应中的其他对象。我的问题是,我如何还能坚持并从ViewModel中的天气响应中访问偏移量和时区?

0 个答案:

没有答案