I have a fragment:
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
})
}
}
In my fragment, I have a instance of StudentsViewModel which is initiated in onViewCreated(...)
.
In, StudentsViewModel
, students
is a LiveData
:
class StudentsViewModel : ViewModel() {
val students = liveData(Dispatchers.IO) {
...
}
}
Back to MyFragment
, in function updateStudentList()
I get compiler error complaining the this
parameter I passed in to .observe(this, Observer{...})
that Use viewLifecycleOwner as the LifecycleOwner
Why I get this error? How to get rid of it?
question from:
https://stackoverflow.com/questions/59521691/use-viewlifecycleowner-as-the-lifecycleowner 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…