ViewModel在Android Studio中如何在幕后处理配置更改?

huangapple go评论57阅读模式
英文:

How does ViewModel in Android Studio handle configuration change behind the scenes?

问题

我一直在研究ViewModels,但让我困惑的是ViewModels如何在幕后处理配置更改,这里有一个示例。

ViewModel

class InitiateviewModels: ViewModel() {
    var list: MutableLiveData<MutableList<Int>> = MutableLiveData()

    fun fillingList(){
        var Integerlist = mutableListOf<Int>(1,2,3,4,5)
        list.setValue(Integerlist)
    }
}

ViewModel类中,每当调用fillingList()方法时,我都会向list属性附加一个新的Integer列表。

MainActivity

class MainActivity : AppCompatActivity() {
    lateinit var Initiation: InitiateviewModels
    lateinit var text: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Initiation = ViewModelProvider(this)[InitiateviewModels::class.java]
        text = findViewById(R.id.textView1)
        Initiation.fillingList()

        Initiation.list.observe(this, Observer{
            text.text = it.toString()
            Log.d("Answers", "${it?.size}")
            Log.d("Answers", "From Viewmodel ${Initiation.list.value?.size}")
        })
    }
}

MainActivity中,我们调用Initiation.fillingList(),将整数列表Integerlist附加到ViewModel中的list属性,然后我们附加观察器到list属性,我们记录列表的大小并在textview上显示列表。

配置更改后列表大小,从观察器和直接从ViewModel属性获取

UI的外观

每次配置更改时,OnCreate函数都会停止并重新启动,这意味着OnCreate会再次调用,如果再次调用OnCreate,那么它不会再次调用Initiation.fillingList()吗?这意味着每次屏幕旋转都会增加list属性的size吗?

那么,首次加载应用程序时,list属性的大小将为5,然后为10,15,20,每次屏幕旋转都会增加。为什么Initiation.fillingList()被调用时列表没有变得越来越大?根据文档的说法,“这种缓存意味着您无需再次通过常见的配置更改(例如屏幕旋转)重新获取数据。”,在这种情况下它是如何工作的?

我只是在测试概念,玩弄一下。

英文:

I have been playing around with viewModels, however what puzzles me is how ViewModels handle configuration changes behind the scenes, here is an example

Viewmodel

class InitiateviewModels: ViewModel() {
    var list:MutableLiveData&lt;MutableList&lt;Int&gt;&gt; = MutableLiveData()

    fun fillingList(){
        var Integerlist = mutableListOf&lt;Int&gt;(1,2,3,4,5)
        list.setValue(Integerlist)
    }
}

In the ViewModel class, I append the list property with a new Integer list whenever fillingList() method gets called.

MainActivity

class MainActivity : AppCompatActivity() {
    lateinit var Initiation:InitiateviewModels
    lateinit var text:TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Initiation = ViewModelProvider(this)[InitiateviewModels::class.java]
        text = findViewById(R.id.textView1)
        Initiation.fillingList()

        Initiation.list.observe(this, Observer{
            text.text = it.toString()
            Log.d(&quot;Answers&quot;, &quot;${it?.size}&quot;)
            Log.d(&quot;Answers&quot;, &quot;From Viewmodel ${Initiation.list.value?.size}&quot;)

        })
    }
}

In the MainActivity,we call the Initiation.fillingList(), to append the list of integers Integerlist to the list property in the ViewModel, we attach observers to the list property , we Log the size of the list and show the list on the textview

Size of list after a configuration change, both from Observers and directly from the viewmodel property

How the UI looks

Each time the configuration changes, the OnCreate functions stops and gets restarted, meaning OnCreate gets called again, if OnCreate is called again, wouldn't it call Initiation.fillingList() again meaning each screen rotation would increase the list property size by 5?

So when first loading the app the size of the list property would be 5, then 10, 15,20,etc everytime the screen is rotated. What could possibly be the reason for the list not becoming bigger and bigger everytime the Initiation.fillingList() is called?

According to the docs This caching means that you don’t have to fetch data again through common configuration changes, such as a screen rotation., how does this work in this case scenario?

I was just playing around, testing concepts out.

答案1

得分: 0

请看一下你的这段代码:

fun fillingList(){
    var Integerlist = mutableListOf<Int>(1,2,3,4,5)
    list.setValue(Integerlist)
}

你并没有向现有列表添加或扩展内容。每次调用此函数时,你都在替换 LiveData 的列表为一个新的列表,因此当你检查 LiveData 的内容时,它的大小始终是相同的。

顺便提一下,变量和属性的名称不应该以大写字母开头——这样命名会导致阅读时很令人困惑,因为按照约定这种命名方式意味着你正在访问静态的 object 而不是类的实例。

英文:

Look at this code of yours more closely:

fun fillingList(){
    var Integerlist = mutableListOf&lt;Int&gt;(1,2,3,4,5)
    list.setValue(Integerlist)
}

You are not adding to or enlarging an existing list. You are replacing the LiveData's list with a new one each time this is called, so when you inspect the LiveData contents it is always the same size.

By the way, variables and property names should not start with a capital letter--that is very confusing to read because that kind of naming by convention would me you're accessing a static object rather than an instance of a class.

huangapple
  • 本文由 发表于 2023年6月30日 03:46:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定