首页 > 解决方案 > 如何避免不必要的api调用,只有在服务器端发生一些变化时才执行api调用

问题描述

fun getNotifications(priorityNum: Int) =
        object : NetworkBoundResource<List<Notification>, Resource<List<Notification>>>(exec) {
            override fun saveCallResult(item: Resource<List<Notification>>) {
                item.data!!.forEach {
                    val id = db.notification().insert(it)
                    if (id == -1L) {
                        db.notification().update(
                            it.id,
                            it.subject,
                            it.description,
                            it.priority,
                            it.community,
                            it.createdTime
                        )
                    }
                }
            }

            override fun shouldFetch(data: List<Notification>?) = true

            override fun loadFromDb(): LiveData<List<Notification>> {
                return db.notification().getAllNotifications()
            }

            override fun createCall(): LiveData<ApiResponse<Resource<List<Notification>>>> =
                api.getNotifications(pref.userId!!, priorityNum)

        }.asLiveData()

我在本地数据库的存储库中使用了类似的东西。我想要的是您可以看到 shouldFetch() 始终为真,即使数据没有更改也会导致 API 调用。因此,这会导致不需要的 API 调用。如何避免这种情况并仅在服务器端有新的插入或更新时才调用后端

标签: androidkotlinsynchronizationandroid-sqliteandroid-room

解决方案


推荐阅读