带有LiveData的MVVM中的View和ViewModel之间的通信 [英] Communication between view and ViewModel in MVVM with LiveData

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

问题描述

ViewModelView之间进行通信的正确方法是什么,Google architecture components使用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是一个hacky解决方案,EventBus(以我的经验)总是会带来麻烦.

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

前一段时间,我在阅读Kotlin Coroutines的Google CodeLabs时发现了一个名为ConsumableValue的类,我发现它是一个很好的,干净的解决方案,对我很有帮助(

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.

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

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