简体   繁体   English

Retrofit 响应保留旧数据并将新数据添加到 editText 搜索

[英]Retrofit responses keep the old data and add the new one to that for editText search

I am getting data from an API with editText search.我正在使用 editText 搜索从 API 获取数据。 At first search it works as expected but on second and so on, it will not show the only new response, instead it keeps old one and adds new one to end of it.起初搜索它按预期工作但在第二个等等,它不会显示唯一的新响应,而是保留旧响应并在其末尾添加新响应。 It acts like it's caching previous ones.它就像在缓存以前的一样。 How can i fix that to show only last search word results?我该如何解决它以仅显示最后的搜索词结果?

Fragment:分段:

var job: Job? = null
binding.etSearchNews.addTextChangedListener { editable ->
    job?.cancel()
    job = MainScope().launch {
        delay(Constants.SEARCH_DELAY)
        editable?.let {
            if (editable.toString().isNotEmpty()) {
                viewModel.searchNews(editable.toString())
            }
        }
    }
}

viewModel.searchNews.observe(viewLifecycleOwner) {
    when (it) {
        is Resource.Success -> {
            hideProgressBar()
            it.data?.let { response ->
                newsAdapter.differ.submitList(response.articles.toList())
            }
        }
        is Resource.Error -> {}
        is Resource.Loading -> {}
    }
}

Adapter:适配器:

private val differCallback = object: DiffUtil.ItemCallback<Article>() {
    override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean {
        return oldItem.url == newItem.url
    }

    override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean {
        return oldItem == newItem
    }
}

val differ = AsyncListDiffer(this, differCallback)

API: API:

@GET("v2/everything")
suspend fun searchNews(
    @Query("q") query: String,
    @Query("page") number: Int = 1,
    @Query("pageSize") size: Int = Constants.PAGE_SIZE,
    @Query("apiKey") key: String = Constants.API_KEY
): Response<NewsResponse>

I've tried to add but no luck:我试图添加但没有运气:

@Headers("Cache-Control: no-cache") 

After spending a day to solve this, I've found the answer finally.花了一天时间解决这个问题后,我终于找到了答案。 It was because of i haven't properly clear the response before.这是因为我之前没有正确清除响应。 It needs to be cleaned in addTextChangedListener so every new try will start on fresh response.它需要在addTextChangedListener中清理,这样每次新的尝试都会从新的响应开始。

Also for leaving the fragment and coming back to it data refresh and scroll position changes problem, i added hasFocus to avoid it:同样为了离开片段并返回它数据刷新和滚动 position 更改问题,我添加了hasFocus来避免它:

So, SearchFragment looks like this:所以,SearchFragment 看起来像这样:

        var job: Job? = null
        binding.etSearchNews.addTextChangedListener { editable ->
            job?.cancel()
            job = MainScope().launch {
                delay(Constants.SEARCH_DELAY)
                editable?.let {
                    if (editable.toString().isNotEmpty()) {
                        if (binding.etSearchNews.hasFocus()) {
                            viewModel.searchNewsResponse = null
                            viewModel.searchNewsPage = 1
                            viewModel.searchNews(editable.toString())
                        }
                    } else {
                        newsAdapter.differ.submitList(listOf())
                    }
                }
            }
        }

PS I didn't see that code in the tutorial, watched twice that part. PS 我没有在教程中看到该代码,看了两遍那部分。 I hope it helps to others.我希望它对其他人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM