Using @Assisted
annotation with savedStateHandle and by viewModels()
it's possible to inject SavedStateHandle object to ViewModel in modules that are not dynamic feature modules with dagger hilt as
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val viewModel: MainActivityViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
class MainActivityViewModel @ViewModelInject constructor(
@Assisted savedStateHandle: SavedStateHandle
) : ViewModel() {
val stringData = savedStateHandle.getLiveData<String>("hello_world")
}
but it's not possible for dynamic feature modules to do like this. How is it done with dynamic feature module ViewModels?
My ViewModel is
Creating generic
FragmentFactory
for SavedStateHandle withViewModel factory for ViewModel
And creating ViewModel using the DashBoardViewModelFactory in Fragment as
Here you can see the full implementation in action. I wasn't able to find the source i used to implement this solution, if you can comment the link, i would like to give credit to author.