I am trying to call a suspend function in my Android project.
I am using init block in view model class and calling suspend function which is fetching data from firestore.
But this is giving me error.
Please suggest What should I do?
init {
_collegeList = getCollegeData() // giving error
// error: Suspend function 'getCollegeData' should be called only from a coroutine or another suspend function
}
This is my data class file
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
}
>Solution :
Note that suspend functions must be called within another suspend function (which init is not) or within a coroutine (which you did not launch).
init {
viewmodelScope.launch {
_collegeList = getCollegeData()
}
}
You should familiarize yourself with suspend functions and coroutine. You can start here: https://kotlinlang.org/docs/coroutines-basics.html