Search code examples
androidandroid-room

Android room: Don't override properties with null


class ArticleResponse(
    val id: Int,
    val previewContent: String
)

fun ArticleResponse.mapToEntity() = Article(
    id = id,
    previewContent = previewContent,
    content = null
)

class SingleArticleResponse(
    val id: Int,
    val content: String
)

fun SingleArticleResponse.mapToEntity() = Article(
    id = id,
    previewContent = null,
    content = content
)

@Entity(tableName = "articles")
class Article(
    @PrimaryKey
    @ColumnInfo(name = "id")
    val id: Int,

    @ColumnInfo(name = "preview_content")
    val previewContent: String?,

    @ColumnInfo(name = "content")
    val content: String?
)

Explanation:
When you look at the code, you have to know that a call to API-Endpoint X gives me a list of ArticleResponse. This response doesn't give me the content property.

When I then want to view the article, I call API-Endpoint Y, which gives my SingleArticleResponse as a Response. This response doesn't give me the previewContent property.

Problem:
No matter what I do, one of the properties content or previewContent will always be null in my local database.

Question:
How can I tell Room, that it should not override the property with null, if it previously has not been null? Is this possible?


Solution

  • I think the easiest and most robust way to do this is to have 6 separate update queries and run them all inside a transaction.

    @Dao
    interface ArticleDAO {
        @Query("UPDATE Article SET content = :content WHERE id = :id")
        suspend fun updateContent(id: Int, content: String)
    
        @Query("UPDATE Article SET previewContent = :previewContent WHERE id = :id")
        suspend fun updatePreviewContent(id: Int, previewContent: String)
    
        //Other update queries here
    }
    
    fun updateArticle(article: Article) {
        database.withTransaction {
            if(article.content != null) {
                articleDao.updateContent(article.id, article.content)
            }
            if(article.previewContent != null) {
                articleDao.updatePreviewContent(article.id, article.previewContent)
            }
    
            //Other updates here ...
        }
    }
    

    Let me know if this answers your question.