I have created a coroutine inside a function to achieve, through the withContext, that the thread waits for the result of the get() launched to firestore. However, it seems that the get() method creates a separate thread, so I can't get the coroutine to wait for the variables to be assigned their corresponding values. The execution continues, and the variables are left with their default values, not with the values collected in firestore.
How should I use the coroutine so that it expects the result requested from the firestore via the get() method? Is there an alternative way to do what I want?
GlobalScope.launch(Dispatchers.Main) {
val recyclerView: RecyclerView = view.findViewById(R.id.recycler1)
recyclerView.layoutManager = LinearLayoutManager(context)
val database = FirebaseFirestore.getInstance()
withContext(Dispatchers.IO) {
database.collection("grupos").document("2").get().addOnSuccessListener {
nombreEvent = it.getString("name")
artista = it.getString("artista")
descripcion = it.getString("descripcion")
lugar = it.getString("lugar")
imagen = it.getString("imagen")
}
}
val adapterRec = RecyclerAdapter( listOf(Grupo("id", nombreEvent, artista, descripcion, lugar,imagen)))
recyclerView.adapter = adapterRec
}
I have already found the solution to the problem I was posing with this coroutine; First, I had to use the await() function so that the main thread would wait for the response of the query launched. On top of that, I had to wrap everything inside a try..catch to catch the exception if no data was found in the query.