How do I correctly create a ViewModel in a `Compon...
# android
l
How do I correctly create a ViewModel in a
ComponentDialog
(not
DialogFragment
)? There is no
by viewModels()
.
m
you mean bind the viewmodel?
l
Yes
Create a reference to it inside the ComponentDialog
m
l
Yes, but
ComponentDialog
doesn't extend
DialogFragment
I suppose it's not possible for a
ComponentDialog
to have its own
ViewModel
, as
ComponentDialog
is not a
ViewModelStoreOwner
.
m
mmm, i think you can provide an extension or a delegate function for getting the viewmodel
l
How?
This is possible only in `Fragment`s and `Activity`s
Not in a
Dialog
m
Did you have this line when creating the viewmodel instance in DialogFragment?
private val viewModel by viewModels<SomeViewModel>(ownerProducer = { this.requireParentFragment() })
l
I don't use a
DialogFragment
I use a
ComponentDialog
, which doesn't extend the
DialogFragment
(or
Fragment
)
It has no
viewModels()
extension function
m
ah, what dependencies related to the viewmodel aspect do you have in app's build.gradle?
check if you can add this library:
implementation "androidx.lifecyclelifecycle viewmodel ktx2.2.0-rc03"
kapt "androidx.lifecyclelifecycle compiler2.2.0-rc03"
l
I have these dependencies in project. It seems not possible. Thank you for your efforts.
m
Are you using the mentioned delegates in another fragments/activities?
l
Yes, and they work
The problem is,
ComponentDialog
is not a
Fragment
.
It cannot have a ViewModel of its own
Thank you for your help.
m
yes, i know, but, there is some ways to use the lifecycle attributes inside the component dialog. this link explin a more bit about this: https://proandroiddev.com/dialogs-in-android-mvvm-5d6e1ca53b19 the idea is using the lifecycle observers to delegate the creation and the binding of the viewmodel
l
The article only mentions `DialogFragment`s everywhere, not `Dialog`s.
It also mentions a custom View as Dialog, but there the ViewModel is inside the Activity, which shows the dialog.
It also uses DataBinding.
m
wait, dialog? mm, where is the dialog opening/showing? in a fragment? activity? afaik, the dialog contains callbacks for the dialog closing or the button (ok, cancel) click events, have you tried using a callback that includes the negative/positive actions and pass them in the dialog invokation?
i
You need a ViewModelStoreOwner to store ViewModels, yes. A Dialog (and ComponentDialog) are at the same level as View - you'd need to go up one more layer to DialogFragment and Fragment if you want a ViewModelStoreOwner
👍 1
🙏 1