Save transient field in Room Database

Viewed 317

Consider the following data model where status is provided by the API at the top level and message is provided at a nested level (this isn't really the case but just to illustrate the problem):

data class (
    @Json(name = "status")
    val status: Int,

    @Transient
    val message: String
)

Now, suppose I want to save this data model into my database. I'd change the model like so:

data class (
    @ColumnInfo(name = "status")
    @Json(name = "status")
    val status: Int,

    @ColumnInfo(name = "message")
    @Transient
    val message: String
)

the message field will not be saved into the database due to the Transient annotation. But what if I want to? How can I force Room to save the field but Moshi to ignore it.

The problem is I have no control over this API, or how it would change in the future, so removing @Transient and changing the name to some random complicated string is not an ideal solution, even if it will fix the problem.


Found a couple of related issues on Moshi:

Apparently this is an age-old issue...

1 Answers

Maybe, can you use a mapper between your object and Room database ?

Like:

data class MessageEntity(
    @ColumnInfo(name = "status")
    val status: Int,
    @ColumnInfo(name = "message")
    val message: String
) {
// ... 
}
data class Message (
    @Json(name = "status")
    val status: Int,

    @Transient
    val message: String
) {
 fun toEntity(): MessageEntity {// ...}
 fun fromEntity(e: MessageEntity): Message {// ...} // or Extensions
}
Related