https://kotlinlang.org logo
#dagger
Title
# dagger
s

Shaun Plummer

01/18/2019, 10:26 AM
What's the recommended way of passing a fragment argument to a view model constructor?
Copy code
/**
         * Creates a new instance of [MyFragment].
         */
        fun newInstance(id: Int): Fragment {

            val args = Bundle()
            args.putInt("KEY", id)

            return MyFragment().apply {
                arguments = args
            }
        }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        // data needed in the view model
        val id = arguments?.getInt("KEY")

        viewModel = ViewModelProviders
            .of(this, viewModelFactory)
            .get(MyViewModel::class.java)
    }
I've seen articles which recommend using module constructor arguments. I'd like to avoid having to use something like a setter to provide the
id
value to the view model.