Saya memiliki sebuah fragmen:
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
})
}
}
Dalam fragmen saya, saya memiliki instance StudentsViewModel yang dimulai pada onViewCreated(...)
.
Dalam, StudentsViewModel
, students
adalah LiveData
:
class StudentsViewModel : ViewModel() {
val students = liveData(Dispatchers.IO) {
...
}
}
Kembali ke MyFragment
, dalam fungsi updateStudentList()
saya mendapatkan error compiler mengeluh this
parameter saya melewati ke .observe(this, Observer{...})
yangUse viewLifecycleOwner as the LifecycleOwner
Mengapa saya mendapatkan kesalahan ini? Bagaimana cara menghilangkannya?
IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()