数据绑定:ViewModel 不应该有对视图的引用,但是......?

Databinding: A ViewModel should not have a reference to the views, but...?

先决条件

所以是的,有很多类似的问题,但我找不到这个特定问题的答案:显然最好不要让 viewModel 持有对 Android 框架的任何引用 类,还有浏览量。 但是!

如果我使用数据绑定,我可以有一个如下所示的 xml 布局:

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewModel"
            type="SomeViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <Button
            android:id="@+id/myButtpn"
            style="@style/mybuttonStyle"
            android:onClick="@{viewModel::onButtonClicked}"/>
        
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

现在希望在我的 SomeViewModel:

中找到这样的方法
fun onButtonclicked(view: View) {
    // I don't need the parameter, but Android needs it to be there
}

但我也可以在布局中像这样引用我的方法:

android:onClick="@{() -> viewModel.onButtonClicked()}"

现在我在 viewModel 中的方法不需要获取视图:

fun onButtonclicked() {
    // all fine
}

实际问题:

它真的有影响吗?显然,我将 viewModel 视图作为函数参数呈现,然后被忽略,所以这看起来不太好而且看起来有点浪费。但据我所知,viewModel 绝不会引用它们。那么这有什么不好的吗?

另一方面,将此 lambda 放入 xml 看起来并不那么性感,但这似乎是典型的做法。它有任何(缺点)优点吗?

第三:这两种方法在性能方面会有什么不同吗?

Does it actually make a difference? Obviously, I am presenting the viewModel views as function parameters, that then get ignored, so this doesn't look great and seems a bit wasteful. But at no time the viewModel holds any reference to them, in my understanding. So is this bad in any way?

您不希望 ViewModel 保留对视图的引用的最大原因之一是因为您的 ViewModelFragment 的生命周期更长。现在你有内存泄漏。

此外,ViewModel(s) 通常应该用于公开 public 值,这些值反过来会驱动 UI 更新和布局,如许多 MVVM 模式中指定的那样.

本质上,databinding 允许您通过删除将这些项目绑定到片段中的 Views 所需的所有样板代码来执行此操作。您会看到 Android 生成 databinding 类 正是这样做的。

On the other hand, putting this lambda into the xml doesn't look so sexy, but it seems to be the typical practice. Doies it have any (Dis-)Advantages?

除了构建时间性能之外没有其他缺点。由于现在您已经有了这些 databinding 代码生成,因此在构建期间,当您在当前模块中进行切换时,您将生成更多代码。

这不是看起来不性感的问题,而是减少将 ViewModel 绑定到您的视图的样板代码。如果您不在 xml 中执行此操作,您将在 FragmentActivity 中执行此操作。完全一样。

And third: Would there be any difference between the two approaches in terms of performance?

我假设运行时性能?不,没有任何好处或缺点。