Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we call suspend function in init block in Kotlin?

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
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading