Now I using the viewModelFactory to init the argument for viewModel in fragment.
class MyFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding = FragmentMyBinding.inflate(inflater)
binding.lifecycleOwner = this
val argument = MyFragmentArgs.fromBundle(requireArgument()).myArgument
val viewModelFactory = MyViewModelFactory(myArgument, application)
binding.viewModel = ViewModelProvider(
this, viewModelFactory).get(MyViewModel::class.java)
return binding.root
}
}
class MyViewModelFactory(
private val myArgument: MyArgument,
private val application: Application) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MyViewModel::class.java)) {
return MyViewModel(myArgument, application) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
Compare to the hilt dependency inject way, is there a way to pass argument to viewModel directly?