You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
How to create a ViewModelComponent that has SavedStateHandle as it's constructor parameter?
I'm migrating from Hilt.
The issue I'm solving is that I've ViewModelScope'd dependencies, that need SavedStateHandle to be injected into them.
It's not just ViewModel, that takes SavedInstanceState, but also the ViewModel-s dependency.
Consider
@Inject
class HomeFragment(createViewModel: (SavedInstanceState) -> HomeViewModel) {
private val viewModel by viewModel(createViewModel) // using ViewModelExtensions
}
@Inject
class HomeViewModel(
@Assisted savedInstanceState: SavedInstanceState,
private val flow: GenericFlowController
) { }
interface HomeFlowController: GenericFlowController { }
interface GenericFlowController {
abstract val type: Type
enum class Type {
HOME, DETAIL, RANDOM
}
}
@Inject
class OtherDependency() { }
@ViewModelScoped
@Inject
class HomeFlowControllerImpl(
savedStateHandle: SavedStateHandle,
private val otherDependency: OtherDependency
): HomeFlowController { }
@ViewModelScoped
abstract class ViewModelComponent( @get:Provides protected val savedStateHandle: SavedStateHandle) {
// this one is quite complicated, is it even doable with Kotlin-Inject? Any alternatives?
@Provides
fun providesGenericFlowController(
controllers: Set<@JvmSuppressWildcards GenericFlowController>
): GenericFlowController = controllers.first { it.type == savedStateHandle[GenericFlowController.Keys.FLOW_TYPE] }
}
@IntoSet
@Provides
fun HomeFlowControllerImpl.bindIntoSet(): GenericFlowController = this
@Provides
fun HomeFlowControllerImpl.bind(): HomeFlowController = this
// [... binding other types ...]
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
How to create a ViewModelComponent that has SavedStateHandle as it's constructor parameter?
I'm migrating from Hilt.
The issue I'm solving is that I've ViewModelScope'd dependencies, that need
SavedStateHandle
to be injected into them.It's not just ViewModel, that takes
SavedInstanceState
, but also the ViewModel-s dependency.Consider
Beta Was this translation helpful? Give feedback.
All reactions