【问题标题】:ViewModel, LiveData with Firestore causing StackOverflowError: stack size 8MBViewModel,带有 Firestore 的 LiveData 导致 StackOverflowError:堆栈大小 8MB
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2021-12-15
      • 1970-01-01
      相关资源
      最近更新 更多