kotlin 中的房间实时数据同步策略与 Rest Api

问题描述

我正在使用 https://newsapi.org/ 创建一个应用程序。 应用程序的工作是我获取 json 响应并使用 remotDataSource 将其存储在房间数据库中。该应用程序运行良好,但有时也会在房间中创建重复项,因此我必须检查插入数据是否插入。 如果房间中已经存在数据,则需要拒绝。 帮助我如何做到这一点:)

一件重要的事情是我参考这个项目做了这个。 https://itnext.io/android-architecture-hilt-mvvm-kotlin-coroutines-live-data-room-and-retrofit-ft-8b746cab4a06

道:

@Query("SELECT * FROM article_table")
fun getAllNews(): LiveData<List<News>>

@Query("SELECT * FROM article_table WHERE id = :id LIMIT 1")
fun getSingleNews(id: Int): LiveData<News>

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(newsList: List<News>)

@Insert
suspend fun insert(news: News)

存储库:

fun getArticle(id: Int) = performGetoperation(
        databaseQuery = {localDataSource.getSingleNews(id)},networkCall = {remoteDataSource.getArticle(id)},saveCallResult = {localDataSource.insert(it)}
)

fun getNews() = performGetoperation(
    databaseQuery = {localDataSource.getAllNews() },networkCall = {remoteDataSource.getNews() },saveCallResult ={ localDataSource.insertAll(it.articles) }
)

服务接口:

@Headers("x-api-key: 22b4fbcf3a2d491d87d7435e1ea83061")
@GET("v2/top-headlines")
suspend fun getAllNews(@Query("country") country: String = "in"): Response<NewsList>

@GET("v2/top-headlines?country=us/{id}")
suspend fun getSingleNews(@Path("id") id: Int): Response<News>

远程:

suspend fun getNews() = getResult { newsService.getAllNews() }
suspend fun getArticle(id: Int) = getResult { newsService.getSingleNews(id)}

实体:

@PrimaryKey(autoGenerate = true)
val id: Int,val author: String?,val title: String?,val description: String?,val url: String?,val urlToImage: String?,val content: String?

我需要的只是检查来自服务器的传入数据,如果数据已经在房间中,则它希望被忽略,否则添加到房间并查看。 提前致谢:)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)