MVVM 中视图和 ViewModel 之间的通信与 LiveData [英] Communication between view and ViewModel in MVVM with LiveData

查看:47
本文介绍了MVVM 中视图和 ViewModel 之间的通信与 LiveData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ViewModelView 之间通信的正确方式是什么,Google 架构组件 使用 LiveData> 其中视图订阅更改并相应地更新自身,但这种通信不适用于单个事件,例如显示消息、显示进度、隐藏进度等.

What is a proper way to communicate between the ViewModel and the View, Google architecture components give use LiveData in which the view subscribes to the changes and update itself accordingly, but this communication not suitable for single events, for example show message, show progress, hide progress etc.

Google 示例中有一些像 SingleLiveEvent 这样的技巧,但它仅适用于 1 个观察者.一些开发人员使用EventBus,但我认为当项目增长时它会很快失控.

There are some hacks like SingleLiveEvent in Googles example but it work only for 1 observer. Some developers using EventBus but i think it can quickly get out of control when the project grows.

有没有方便正确的实现方式,你是如何实现的?

Is there a convenience and correct way to implement it, how do you implement it?

(也欢迎 Java 示例)

推荐答案

是的,我同意,SingleLiveEvent 是一个笨拙的解决方案,而 EventBus(以我的经验)总是会导致麻烦.

Yeah I agree, SingleLiveEvent is a hacky solution and EventBus (in my experience) always lead to trouble.

不久前我在阅读 Google CodeLabs for Kotlin Coroutines 时发现了一个名为 ConsumableValue 的类,我发现它是一个很好的、干净的解决方案,对我很有帮助(ConsumableValue.kt):

I found a class called ConsumableValue a while back when reading the Google CodeLabs for Kotlin Coroutines, and I found it to be a good, clean solution that has served me well (ConsumableValue.kt):

class ConsumableValue<T>(private val data: T) {
    private var consumed = false

    /**
     * Process this event, will only be called once
     */
    @UiThread
    fun handle(block: ConsumableValue<T>.(T) -> Unit) {
        val wasConsumed = consumed
        consumed = true
        if (!wasConsumed) {
            this.block(data)
        }
    }

    /**
     * Inside a handle lambda, you may call this if you discover that you cannot handle
     * the event right now. It will mark the event as available to be handled by another handler.
     */
    @UiThread
    fun ConsumableValue<T>.markUnhandled() {
        consumed = false
    }
}

class MyViewModel : ViewModel {
    private val _oneShotEvent = MutableLiveData<ConsumableValue<String>>()
    val oneShotEvent: LiveData<ConsumableValue<String>>() = _oneShotData

    fun fireEvent(msg: String) {
        _oneShotEvent.value = ConsumableValue(msg)
    }
}

// In Fragment or Activity
viewModel.oneShotEvent.observe(this, Observer { value ->
    value?.handle { Log("TAG", "Message:$it")}
})

简而言之,handle {...} 块只会被调用一次,因此返回屏幕时无需清除该值.

In short, the handle {...} block will only be called once, so there's no need for clearing the value if you return to a screen.

这篇关于MVVM 中视图和 ViewModel 之间的通信与 LiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆