【发布时间】:2020-09-12 04:31:54
【问题描述】:
我正在从 firestore 获取一个集合并在 recyclerview 中显示。该集合很小,只有 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
}
【问题讨论】:
标签: android firebase kotlin android-livedata android-viewmodel