Android Room is partially updated if you exit

I ran into a problem when I'm not sure how to solve it. The project I'm working on now has a model that partially consists of backend data and data from a local database. So I'm trying to Archive something like this:

Article: [Bouquet of Information] and [boolean Subscribed]

The signed field is bound to the device and should not reflect data on the server. My question is whether it is possible to implement some createIfNotExit () method in the Room, which handles the following cases:

  • Article not submitted locally: save a copy and set the subscription to false
  • This article: update all information and save Subscribe-Mark intact

My idea is to split the model into a separate subscription model containing a link to the article. That way, I could implement it simply via @Update(OnConfict=Update) , etc.

Is there a way to implement a simple @Query method in a DAO that does what I want?

Sorry if this is really a basic question, but I could not find any materials on the best methods of handling this case.

Thank you in advance!

+5
source share
1 answer

For example, your entity:

 @Entity(tableName = "articles") public final class Article { @PrimaryKey public long serverId; public String title; public String url; public boolean isSubscribed; } 

You can write this method in DAO:

 @Query("INSERT OR REPLACE INTO articles (serverId, title, url, isSubscribed) VALUES (:id, :title, :url, COALESCE((SELECT isSubscribed FROM articles WHERE id = :id), 0));") void insertOrUpdateArticle(long id, String title, String url); 

Another option is to write this logic in your repository and use two simple operations: select and update

+3
source

Source: https://habr.com/ru/post/1269826/


All Articles