代码之家  ›  专栏  ›  技术社区  ›  Rishabh Aggarwal

我们可以在Kotlin的init块中调用suspend函数吗?

  •  0
  • Rishabh Aggarwal  · 技术社区  · 2 年前

    我正试图在我的Android项目中调用一个挂起函数。 我在视图模型类中使用init块,并调用从firestore获取数据的suspend函数。 但这给了我错误。 我该怎么办?

     init {
            _collegeList = getCollegeData() // giving error
    // error: Suspend function 'getCollegeData' should be called only from a coroutine or another suspend function
        }
    

    这是我的数据类文件

    private suspend fun getListOfColleges(): List<DocumentSnapshot>{
            val db = FirebaseFirestore.getInstance()
            val snapshot = db.collection("Colleges").get().await()
            return snapshot.documents
        }
    
        suspend fun getCollegeData(): ArrayList<College>{
            try {
                val collegeList = getListOfColleges()
                for(dS in collegeList){
                    val college:College? = dS.toObject(College::class.java)
                    if(college != null){
                        collegeData.add(college)
                    }
                }
            } catch (e: Exception){
                Log.d("Fetching Data","${e.message}")
            }
            return collegeData
        }
    
    1 回复  |  直到 2 年前
        1
  •  -1
  •   dominicoder    2 年前

    请注意,挂起函数必须在另一个挂起函数( init 不是)或在协同程序中(您没有启动)。

    init {
        viewmodelScope.launch {
            _collegeList = getCollegeData()
        }
    }
    

    您应该熟悉suspend函数和协同程序。您可以从这里开始: https://kotlinlang.org/docs/coroutines-basics.html