Tengo un fragmento:
class MyFragment : BaseFragment() {
// my StudentsViewModel instance
lateinit var viewModel: StudentsViewModel
override fun onCreateView(...){
...
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(this).get(StudentsViewModel::class.java)
updateStudentList()
}
fun updateStudentList() {
// Compiler error on 'this': Use viewLifecycleOwner as the LifecycleOwner
viewModel.students.observe(this, Observer {
//TODO: populate recycler view
})
}
}
En mi fragmento, tengo una instancia de StudentsViewModel que se inicia en onViewCreated(...)
.
En, StudentsViewModel
, students
es un LiveData
:
class StudentsViewModel : ViewModel() {
val students = liveData(Dispatchers.IO) {
...
}
}
Volver a MyFragment
, en función de updateStudentList()
recibo compilador de error que se queja el this
parámetro pasé para .observe(this, Observer{...})
queUse viewLifecycleOwner as the LifecycleOwner
¿Por qué me sale este error? Cómo deshacerse de él?
IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()