简体   繁体   English

Android Room with LiveData + ViewModel 刷新问题

[英]Android Room with LiveData + ViewModel Refresh Question

I have a small app I am using to try learn more about some of the newer Android components.我有一个小应用程序,用于尝试了解有关一些较新的 Android 组件的更多信息。 I'm finding it difficult to find information and understand how best to do what I want.我发现很难找到信息并了解如何最好地做我想做的事。

Currently: Open app -> load data + stores in DB -> display data in list当前:打开应用程序 -> 加载数据 + 在数据库中存储 -> 在列表中显示数据

I want to be able to query data again upon button press.我希望能够在按下按钮时再次查询数据。 I have 2 buttons, 1 to fetch data again, 1 to delete the list data from the DB.我有 2 个按钮,1 个用于再次获取数据,1 个用于从数据库中删除列表数据。

Problem is that it seems you cannot refresh if you are observing on an instance of LiveData, which I am.问题是,如果您正在观察 LiveData 的一个实例,我似乎无法刷新。 I understand that however the way I found to actually do a Network call and store in the Database returns an instance of LiveData and I am not sure how best to proceed.我知道,但是我发现实际执行网络调用并存储在数据库中的方式返回了一个 LiveData 实例,我不确定如何最好地进行。

Let me show you the code.让我向您展示代码。

Fragment分段

private val viewModel: quoteViewModel by viewModels()
private lateinit var binding: FragmentHomeBinding
private lateinit var adapter: QuoteAdapter

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = FragmentHomeBinding.inflate(inflater, container, false)
    return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    initRecyclerView()
    setupRetrieveQuotesObserver()
    setupDeleteDataListener()
    setupFetchNewDataListener()
    setupSwipeToRefresh()
}

private fun initRecyclerView() {
    adapter = QuoteAdapter()
    binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
    binding.recyclerView.adapter = adapter
}

private fun setupDeleteDataListener() {
    binding.removeQuotesButton.setOnClickListener {
        viewModel.removeAllQuotes()
    }
}

private fun setupFetchNewDataListener() {
    binding.getQuotesButton.setOnClickListener {
        viewModel.removeQuotes()
        viewModel.getQuotes()
    }
}

private fun setupRetrieveQuotesObserver() {
    viewModel.quoteLiveDataList.observe(viewLifecycleOwner, Observer { result ->
        when (result.status) {
            NewResult.Status.SUCCESS -> {
                result.data.let { adapter.setItems(ArrayList(result.data)) }
                binding.progressBar.visibility = View.GONE
                binding.swipeContainer.isRefreshing = false
            }

            NewResult.Status.ERROR -> {
                binding.progressBar.visibility = View.GONE
                Snackbar.make(binding.root, "Some error has occurred", Snackbar.LENGTH_SHORT)
                    .show()
            }

            NewResult.Status.LOADING -> {
                binding.progressBar.visibility = View.VISIBLE
            }
        }
    })
}

private fun setupSwipeToRefresh() {
    binding.swipeContainer.setOnRefreshListener {
        viewModel.getQuotes()
    }
}

ViewModel视图模型

val quoteLiveDataList: LiveData<NewResult<List<Quote>>> = repository.quotes

fun getQuotes() = viewModelScope.launch {
    repository.quotes
}

fun removeAllQuotes() = viewModelScope.launch {
    repository.deleteAllQuotes()
}

Repository存储库

    val quotes = performGetOperation(
    databaseQuery = { dao.getAllQuotes() },
    networkCall = { remoteSource.getAllQuotes() },
    saveCallResult = {
        val quotesList = ArrayList<Quote>()

        for (messageString in it.messages.non_personalized) {
            quotesList.add(
                Quote(
                    messageString,
                    FaceImageProvider().getRandomFacePicture(),
                    false
                )
            )
        }

        dao.insertQuotes(quotesList)
    }
)

@WorkerThread
suspend fun deleteAllQuotes() = withContext(Dispatchers.IO) { dao.deleteAllQuotes() }

performGetOperation This is a class I saw online for handling what I want to do. performGetOperation这是我在网上看到的一个类,用于处理我想做的事情。 I think the issue stems from here as it is returning LiveData, I'm not sure how best to fix it我认为问题源于这里,因为它正在返回 LiveData,我不确定如何最好地解决它

fun <T, A> performGetOperation(
databaseQuery: () -> LiveData<T>,
networkCall: suspend () -> NewResult<A>,
saveCallResult: suspend (A) -> Unit
): LiveData<NewResult<T>> =
liveData(Dispatchers.IO) {
    emit(NewResult.loading())
    val source = databaseQuery.invoke().map { NewResult.success(it) }
    emitSource(source)

    val responseStatus = networkCall.invoke()
    if (responseStatus.status == NewResult.Status.SUCCESS) {
        saveCallResult(responseStatus.data!!)

    } else if (responseStatus.status == NewResult.Status.ERROR) {
        emit(NewResult.error(responseStatus.message!!))
        emitSource(source)
    }
}

RemoteDataSource远程数据源

suspend fun getQuotes() = getResult { service.getQuotes() }

getResult获取结果

    protected suspend fun <T> getResult(call: suspend () -> Response<T>): NewResult<T> {
    try {
        val response = call.invoke()
        if (response.isSuccessful) {
            val body = response.body()
            if (body != null) {
                return NewResult.success(body)
            }
        }

        return error("${response.code()} ${response.message()}")
    } catch (e: Exception) {
        return error(e.message ?: e.toString())
    }
}

private fun <T> error(message: String): NewResult<T> {
    Log.d("BaseDataSource", message)
    return NewResult.error("Network called failed due to:  $message")
}

NewResult新结果

data class NewResult<out T>(val status: Status, val data: T?, val message: String?) {

enum class Status {
    SUCCESS,
    ERROR,
    LOADING,
}

companion object {
    fun <T> success(data: T): NewResult<T> {
        return NewResult(Status.SUCCESS, data, null)
    }

    fun <T> error(message: String, data: T? = null): NewResult<T> {
        return NewResult(Status.ERROR, data, message)
    }

    fun <T> loading(data: T? = null): NewResult<T> {
        return NewResult(Status.LOADING, data, null)
    }
}

Apologies for the very long message, but I guess I need to show all the little bits and bobs I'm using.对很长的消息深表歉意,但我想我需要展示我正在使用的所有点点滴滴。 I think the problem is in the Fragment where I do viewModel.quoteLiveDataList.observe , as it is returning a new LiveData if it is called again.我认为问题出在我执行viewModel.quoteLiveDataList.observe的 Fragment 中,因为如果再次调用它,它将返回一个新的 LiveData。 So I'm not sure how I can do another server call and update the DB and return it here.所以我不确定如何进行另一个服务器调用并更新数据库并在此处返回。 Appreciate any help!感谢任何帮助! Thanks谢谢

Use Transformations.switchMap on a MutableLiveData to trigger your repository call like it is done here in the GithubBrowserSample project.使用Transformations.switchMapMutableLiveData喜欢做是为了触发你的资料库调用这里的GithubBrowserSample项目。 This will allow you to implement the refresh functionality -这将允许您实现刷新功能 -

private val _getQuotes = MutableLiveData<Boolean>()

val quotes: LiveData<NewResult<List<Quote>>> = _getQuotes.switchMap { getQuotes ->
    repository.quotes
}

fun getQuotes() {
    _getQuotes.value = true
}

fun refresh() {
    _getQuotes.value?.let {
        _getQuotes.value = it
    }
}

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

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