How to fill spinner with data from room, with MVVM architecture

  android, kotlin, spinner

I want to know the best practice/way to fill any Spinner with data from room db.

I also want to use ViewModel and LiveData (then I’ll move to StateFlow!), but I’m confused with the correct order defining variables.

first I have this in the view model:

val aniosLiveData = anioRepository.anios.asLiveData() // return  LiveData<List<Anio>>

then on the fragment, first the viewmodel declaration:

private val ensayosViewModel: EnsayosViewModel by viewModels()

then, in onViewCreated() I have a block with the binding elements:

 binding.apply {
        recyclerViewEnsayos.apply {
            adapter = ensayosAdapter
            layoutManager = LinearLayoutManager( requireContext())
        spinnerAnio.apply {
            adapter = aniosAdapter  // <- Spinner adapter

I override onCreate() to define an observer, and then I put this lines:

       ensayosViewModel.aniosLiveData.observe(viewLifecycleOwner, {spinnerData ->
        aniosAdapter = ArrayAdapter<Anio>(requireContext(), R.layout.spinner_text_item, spinnerData)

Where/When do I need to declare "aniosAdapter" ? like this: ?

 //At class level
 private lateinit var aniosAdapter : ArrayAdapter<Anio>

Is this the correct way ?
There is another ?? more simpler ?

Thanks in advance!
Best Regards

Source: Android Questions