pass context to ViewModel with a function member not in constructor or factory in Android
Asked Answered
H

0

8

I know that is not a best practice to pass a context to a ViewModel. but I wonder is it okay to get a context instance as a local parameter of a function in the ViewModel?

because in this case the function use the context and release that context reference by the end of the function.

and please assume that we don't want use AndroidViewModel to get application Context.

for example:

class MyViewModel : ViewModel(){

     initColors(context:Context){

             //do something with context like getting colors from resourcse
      }

}

and in fragment:

class Myfrgament:Fragment(){
private val viewModel: LessonFragmentViewModel by viewModels{}
   override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

   viewModel.initColors(requireContext())
}

}

Haemostatic answered 28/12, 2020 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.