https://kotlinlang.org logo
#kodein
Title
i

igor.wojda

11/24/2018, 7:00 PM
I have album detail view witch displays album based on Id passed by intent extra to my Activity. Normally I would inject AlbumDetailsViewModelFactory into Activity, however this time this factory needs additional parameter - id (what is the best way to achieve this? How can we inject this factory into Activity or ViewModel and pass the id?)
s

streetsofboston

11/24/2018, 11:04 PM
Pass the
id
using the
Intent
that starts the Activity. Then when creating an instance of your AlbumDetailsViewModel, provide the
id
by doing
intent.getStringExtra
i

igor.wojda

11/25/2018, 9:01 AM
Let’s me be clear: To obtain VievModel with arguments we have to use custom factory (class extending
ViewModel.Factory
). It would be preferable to inject this factory into activity, however factory requires a bit of configuration (album Id) before it is constructed 🤔
s

streetsofboston

11/25/2018, 5:25 PM
That is true. In our app, we created a extension function on an Activity and Fragment, called
bindViewModel
, that takes a
KodeinAware
as a second receiver, a lambda as a parameter, and uses a custom
ViewModel.Factory
for its implementation. The lambda will return a new
ViewModel
when it is called. This allows for arguments (eg the intent extra) to be provided.
i

igor.wojda

11/26/2018, 9:21 AM
Sounds good @streetsofboston. Can you please share code of these extensions and usage in the Fragment?
3 Views