【问题标题】:How to call AppUpdateManager.startUpdateFlowForResult() from viewmodel?如何从 viewmodel 调用 AppUpdateManager.startUpdateFlowForResult()?
【发布时间】:2023-03-03 05:43:18
【问题描述】:

如何在 android 的 viewmodel 中调用 AppUpdateManager.startUpdateFlowForResult()。它需要一个活动/片段作为参数。

【问题讨论】:

  • 您能否编辑您的问题以包含您的 ViewModel 代码以及您为什么要尝试调用需要 ViewModel 中的活动/片段的东西?

标签: android viewmodel android-mvvm in-app-update


【解决方案1】:

你不应该,你应该使用一个名为 state 的实时数据对象(也许也使用一个枚举) 管理 ViewModel 中的状态,然后观察活动(或片段)中的实时数据并根据状态执行适当的操作。
假设您需要三种状态,并且您需要在 ViewModel 中的某个位置调用AppUpdateManager.startUpdateFlowForResult(),您的代码应如下所示:

enum class State {
    StateOne,
    StateTwo,
    StateThree
}

在您的 ViewModel 中:

val state = MutableLiveData<State>()

...

fun somewhere() {
    ....
    // instead of calling AppUpdateManager.startUpdateFlowForResult() set the proper state
    // I assume its stateThree
    state.postValue(State.StateThree)
}

现在,在你的 activiti 的 onCreate() 中:

viewModel.state.observe(this) { yourstate ->
            yourstate?.also { state ->
                when (state) {
                    State.stateOne -> { 
                        // do something
                    }
                    State.stateTwo -> {
                        // do something
                    }
                    State.stateThree -> {
                        AppUpdateManager.startUpdateFlowForResult()
                    }

                }

            }
        }

我希望它足够清楚

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    相关资源
    最近更新 更多