将livedata传递到查看模型构造函数有效吗?

发布于 2025-01-24 16:17:48 字数 840 浏览 4 评论 0原文

我正在使用MVVM与空间构建一个应用程序,其中一个活动列表在活动中显示。该列表是从Livedata对象中的房间数据库获得的,并在活动中观察到。

在想将另一个项目添加到列表中后,显示了对话框,这会提示用户从可能值列表中选择一个值,但是,如果所选值已经存在于数据库中,则不允许用户按下对话框正按钮。

我已经为活动和对话范围实施了单独的视图模型。两种视图模型都会单独呼叫以从数据库中访问数据,即使它们总是在查看相同的数据。对我来说,这似乎是一种补给者,所以我想知道,使两个ViewModels共享相同数据的最佳方法是什么,只有一个调用从数据库中获取它。

我得到的一个想法是在对话范围构造函数中添加livedata的参数,然后在创建对话fragment viewModel时,我将传递包含从活动ViewModel获得的列表的Livedata的参考。

class AddItemDialogVewModel(items: LiveData<List<Item>>) :
   ViewModel() {

  //check if item to be added already exists in items

}

为ViewModel创建工厂类,然后在DialogFragment中:

val dialogViewModel = ViewModelProvider(this, new AddItemViewModelFactory(activityViewModel.items))
 .get(AddItemDialogViewModel.class);

是否有人看到此问题,并且有更好的方法可以做到这一点。我以前从未见过它,所以我不确定这是好习惯。

谢谢

I'm building an app using MVVM with Room where a list of data is displayed in an activity. The list is obtained from the Room database in a LiveData object and observed in the activity.

Upon wanting to add another item to the list, a DialogFragment is shown which prompts the user to pick a value from a list of possible values, however, if the chosen value is already present in the database, it will not allow the user to press the dialog positive button.

I have implemented separate ViewModels for the Activity and DialogFragment. Both viewmodels make separate calls to access the data from the database, even though they will always be looking at the same data. This to me seems kind of reduntant, so I'm wondering, what would be the best way to make the two viewmodels share the same data, with only one call to fetch it from the database made.

One idea I got is to add a parameter for a LiveData in the DialogFragment constructor, and then when creating the DialogFragment viewmodel, I would pass the reference for the LiveData containing the list, obtained from the activity viewmodel.

class AddItemDialogVewModel(items: LiveData<List<Item>>) :
   ViewModel() {

  //check if item to be added already exists in items

}

create a Factory class for the ViewModel and then in the DialogFragment:

val dialogViewModel = ViewModelProvider(this, new AddItemViewModelFactory(activityViewModel.items))
 .get(AddItemDialogViewModel.class);

Does anyone see any issues with this and is there a better way to do this. I never saw it done before so I'm unsure if it's good practice.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感性不性感 2025-01-31 16:17:48

如果活动和片段从数据库中的表中显示相同的数据,则用户选择的值将始终存在于数据库中。

您想在这里实现什么?

顺便说一下,如果您真正想要做的事情,则不需要为对话框片段实现视图模式。您可以从父活动中使用共享的ViewModel。

您使用共享livedata的方法是正确的。但是将其传递给构造函数并不是正确的方法。

我将使用Kotlin属性代表进行ViewModels。添加以下依赖项:

implementation "androidx.fragment:fragment-ktx:1.4.1"
implementation "androidx.activity:activity-ktx:1.4.0"

Activity ViewModel

class ItemsActivityViewModel : ViewModel() {
    private val _items = MutableLiveData<List<Item>>()
    val items: LiveData<List<Item>> get() = _items
    .
    .
    .
    // Get data from Room Database ...
}

活动

class ItemsActivity : AppCompatActivity() {

    private val viewModel by viewModels<ItemsActivityViewModel>() // Can only be use with an empty constructor ViewModel

    override fun onCreate(savedInstanceState:Bundle) {
        super.onCreate(savedInstanceState)
        viewModel.items.observe(this) { items ->
            // Do something
        }
    }

}

片段

class AddItemDialogFragment : DialogFragment() {

    private val activityViewModel by activityViewModels<ItemsActivityViewModel>()

    override fun onViewCreated(view:View, savedInstanceState:Bundle) {
        activityViewModel.items.observe(viewLifecycleOwner) { items ->
            // Do something
        }
    }
}

,也可以从viewModelProvider创建视图模型。

活动

class ItemsActivity : AppCompatActivity() {

    lateinit var viewModel: ItemsActivityViewModel

    override fun onCreate(savedInstanceState:Bundle) {
        super.onCreate(savedInstanceState)
        viewModel = ... // Create your ViewModel
        viewModel.items.observe(this) { items ->
            // Do something
        }
    }

}

片段

class AddItemDialogFragment : DialogFragment() {

    private lateinit var activityViewModel: ItemsActivityViewModel

    override fun onCreate(savedInstanceState:Bundle) {
        super.onCreate(savedInstanceState)
        activityViewModel = (requireActivity() as ItemsActivity).viewModel
    }

    override fun onViewCreated(view:View, savedInstanceState:Bundle) {
        activityViewModel.items.observe(viewLifecycleOwner) { items ->
            // Do something
        }
    }
}

If the activity and fragment show the same data from a table in the database, the value that the user have chosen will always be present in the database.

What is it that you want to achieve here?

By the way if that's what you really want to do you don't need to implement the ViewModel for the dialog fragment. You can use a shared ViewModel from the parent activity.

Your approach of using a shared LiveData is correct. But passing it in a constructor is not the correct way to do it.

I'm going to use Kotlin Property Delegates for ViewModels. Add these dependencies:

implementation "androidx.fragment:fragment-ktx:1.4.1"
implementation "androidx.activity:activity-ktx:1.4.0"

Activity ViewModel

class ItemsActivityViewModel : ViewModel() {
    private val _items = MutableLiveData<List<Item>>()
    val items: LiveData<List<Item>> get() = _items
    .
    .
    .
    // Get data from Room Database ...
}

Activity

class ItemsActivity : AppCompatActivity() {

    private val viewModel by viewModels<ItemsActivityViewModel>() // Can only be use with an empty constructor ViewModel

    override fun onCreate(savedInstanceState:Bundle) {
        super.onCreate(savedInstanceState)
        viewModel.items.observe(this) { items ->
            // Do something
        }
    }

}

Fragment

class AddItemDialogFragment : DialogFragment() {

    private val activityViewModel by activityViewModels<ItemsActivityViewModel>()

    override fun onViewCreated(view:View, savedInstanceState:Bundle) {
        activityViewModel.items.observe(viewLifecycleOwner) { items ->
            // Do something
        }
    }
}

Or you can create your ViewModel from ViewModelProvider.

Activity

class ItemsActivity : AppCompatActivity() {

    lateinit var viewModel: ItemsActivityViewModel

    override fun onCreate(savedInstanceState:Bundle) {
        super.onCreate(savedInstanceState)
        viewModel = ... // Create your ViewModel
        viewModel.items.observe(this) { items ->
            // Do something
        }
    }

}

Fragment

class AddItemDialogFragment : DialogFragment() {

    private lateinit var activityViewModel: ItemsActivityViewModel

    override fun onCreate(savedInstanceState:Bundle) {
        super.onCreate(savedInstanceState)
        activityViewModel = (requireActivity() as ItemsActivity).viewModel
    }

    override fun onViewCreated(view:View, savedInstanceState:Bundle) {
        activityViewModel.items.observe(viewLifecycleOwner) { items ->
            // Do something
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文