ViewModel, LiveData with Firestore causing StackOverflowErro



我正在从Firestore获取一个集合并在回收器视图中显示。该集合很小,只有 2 个文本少于 10 个字符的文档。当我在不使用架构设计模式的情况下在 recylcerview 中显示它时,它工作正常,但如果我使用 viewmodel 和 livdedata 实现它,我会得到堆栈大小 8MB 错误和应用程序崩溃。我已经搜索了一天,找不到任何相关内容。

fetchNotes(( 被反复调用,addOnSuccessListener(( 中的日志不会命中。

一旦这工作,我将添加存储库。

class HomeActivity : AppCompatActivity() {
private val fab by lazy { findViewById<FloatingActionButton>(R.id.floatingActionButton) }
private val homeAdapter by lazy { HomeAdapter(ArrayList<Note>(),this) }
private val homeRecylerView by lazy {  findViewById<RecyclerView>(R.id.homerecyclerview)}
private val homeViewModel: HomeViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
initUI()
initRecyclerView()
initViewModel()

}
private fun initViewModel() {
homeViewModel.getNotes().observe(this, Observer<List<Note>> { notes ->
homeAdapter.notes = notes
homeAdapter.notifyDataSetChanged()
})
}
class HomeViewModel : ViewModel() {
var tempList:MutableList<Note> =   mutableListOf()
fun getNotes(): LiveData<List<Note>> {
return notes
}
private val notes: MutableLiveData<List<Note>> by lazy {
MutableLiveData<List<Note>>().also {
fetchNotes()
}
}
fun fetchNotes(): MutableLiveData<List<Note>> {
FirebaseUtils.db().collection("notes").document(
FirebaseUtils.auth().currentUser!!.uid
)
.collection("usernotes")
.get()
.addOnSuccessListener { documents ->
for (document in documents) {
tempList.add(document.toObject(Note::class.java))
}
notes.setValue(tempList)
}
.addOnFailureListener { exception ->

}
return notes
}

我想通了。这是由于递归,因为我不熟悉实时数据。我将其修复为

val notes: MutableLiveData<List<Note>> by lazy {
MutableLiveData<List<Note>>()
}