我正试图在我的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
}