Android LiveData get()语法如何工作? [英] How Does Android LiveData get() syntax work?

查看:142
本文介绍了Android LiveData get()语法如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解需要在ViewModel中为LiveData创建获取和设置点,但是我希望了解get()语法在Android中的工作原理.

I understand the need for creating getter and setter points for LiveData in the ViewModel, but I'm looking to understand how the get() syntax works in Android.

即:

val isRealtime: LiveData<Boolean>
    get() = _isRealtime
private val _isRealtime = MutableLiveData<Boolean>()

推荐答案

get()与Android不相关.

get() is not related to Android.

val isRealtime: LiveData<Boolean>
    get() = _isRealtime

此处,get()覆盖了isRealtime属性的自动生成的Kotlin getter函数.因此,它不返回自己的值,而是返回_isRealtime的值.

Here, get() is overriding the automatically-generated Kotlin getter function for the isRealtime property. So, instead of returning its own value, it returns the value of _isRealtime.

我个人建议使用更简单的语法:

Personally, I recommend simpler syntax:

private val _isRealtime = MutableLiveData<Boolean>()
val isRealtime: LiveData<Boolean> = _isRealtime

这两种方法的目的都是为了保持可变性的私密性,因此此类消费者不会意外地更新MutableLiveData.

The objective of either of these is to keep the mutability private, so consumers of this class do not accidentally update the MutableLiveData themselves.

这篇关于Android LiveData get()语法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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