0

I'm making a recyclerview. when using init block, I have problem. I expected code is executed in order. but It's out of order

Some code :

inner class TodoListFragmentRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        val doListDTOs =  ArrayList<DoListDTO>()

        init {
            Log.e("1","1")
            doListListenerRegistration = fireStore.collection("doList").whereEqualTo("doListName",todoList_name).orderBy("doListTimestamp", Query.Direction.DESCENDING).limit(100)
                .addSnapshotListener { querySnapshot, firebaseFirestoreException ->
                    if (querySnapshot == null) return@addSnapshotListener
                    doListDTOs.clear()
                    for (snapshot in querySnapshot.documents) {
                        val item = snapshot.toObject(DoListDTO::class.java)
                        doListDTOs.add(item!!)
                        Log.e("2",doListDTOs.toString())
                        notifyDataSetChanged()
                    }
                }
            Log.e("3",doListDTOs.toString())
        }
}

I want log showed like below order 1 -> 2 -> 3 but, the actual output is 1 -> 3 -> 2

why is this?

As an additional issue, because of above order, last doListDTOs.toString() is null in log 3. but doListDTOs.toString in log 2 have some value. If It's not a order problem, I'd be grateful if you could tell me what the problem was.

csabinho
  • 1,579
  • 1
  • 18
  • 28
서동빈
  • 5
  • 2

1 Answers1

1

When you connect to Firestore and try to request data from firestore DB. you are acutally making a network call which is run via a background thread. Now the main thread first print log for you as 1. and then starts a new thread A (for example). And lastly print 3. But you have to notice that 2 will be print when data is read via thread A and is returned to callback of main thread (IPC) and that's exactly why it shows 3 before 2.

If you need to run 3 after two, you have write code inside firestore callback. when that task is completed, you will iniate your next step.

Hope it helps!

Wajid
  • 2,235
  • 1
  • 19
  • 29
  • 1
    Thank you! I solved this following way "Task combinedTask = Tasks.whenAllSuccess(firstTask, secondTask).addOnSuccessListener(new OnSuccessListener>() { @Override public void onSuccess(List list) { //This is the list that I wanted } });" See the link below https://stackoverflow.com/questions/51859652/how-to-exclude-an-element-from-a-firestore-query Have a nice day! – 서동빈 Oct 07 '19 at 08:35