gpt4 book ai didi

android - 如何再次调用 LiveData Coroutine Block

转载 作者:行者123 更新时间:2023-12-02 11:18:36 25 4
gpt4 key购买 nike

我正在使用 LiveData 的版本“androidx.lifecycle:lifecycle-livedata-ktx:2.2.0-alpha05”。一旦我的 LiveData block 成功执行,我想明确触发它再次执行,例如

  • 我导航到一个 fragment
  • 用户数据加载
  • 我在同一 fragment 中单击删除 btn
  • 用户数据应该刷新

  • 我有一个 fragment ,我在其中观察我的 LiveData,一个带有 LiveData 和 Repository 的 ViewModel:

    View 模型:

      fun getUserLiveData() = liveData(Dispatchers.IO) {

    val userData = usersRepo.getUser(userId)

    emit(userData)
    }


    分段:

    viewModel.getUserLiveData.observe(viewLifecycleOwner,
    androidx.lifecycle.Observer {..


    然后我试图实现这样的期望行为:

    viewModel.deleteUser()

    viewModel.getUserLiveData()


    根据下面的文档,如果 LiveData block 已成功完成并且我放置了 ,它将不会执行而(真)在 LiveData block 内,然后我的数据会刷新,但是我不希望这样做,因为我需要 react 性地更新我的 View 。

    If the [block] completes successfully or is cancelled due to reasons other than [LiveData] becoming inactive, it will not be re-executed even after [LiveData] goes through active inactive cycle.



    也许我错过了如何重用相同的 LiveDataScope 来实现这一目标?任何帮助,将不胜感激。

    最佳答案

    要使用 liveData { .. } block 执行此操作,您需要定义一些命令源,然后在 block 中订阅它们。例子:

    MyViewModel() : ViewModel() {
    val commandsChannel = Channel<Command>()

    val liveData = livedata {
    commandsChannel.consumeEach { command ->
    // you could have different kind of commands
    //or emit just Unit to notify, that refresh is needed
    val newData = getSomeNewData()
    emit(newData)
    }
    }

    fun deleteUser() {
    .... // delete user
    commandsChannel.send(RefreshUsersListCommand)
    }
    }

    你应该问自己一个问题:也许改用普通的 MutableLiveData 会更容易,并自己改变它的值?

    当您可以收集一些数据流(例如来自 Room DB 的 Flow/Flowable)时,livedata { ... } 构建器效果很好,而对于普通的非流源则不太好,您需要自己请求数据。

    关于android - 如何再次调用 LiveData Coroutine Block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58245708/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com