0

I have an Async call, in which callback listener I've put the emitter.onNext(). This async call is inside a for-in (I know the list size). I would like call onComplete() when last element has been emitted in onNext().

for (anItem in itemList) {

     eventsQuery.get()
           .addOnCompleteListener { task ->
               if (task.isComplete) {

                    emitter.onNext(myItemFromTask)

                    if(count == itemList.size){
                         emitter.onComplete()
                    }
                }
           }
 }

The count, as it is a async call, is not bein incremented in the proper way and the onComplete() is never called.

What is the proper way to handle with this situation? I need the onComplete to show the view and remove the loading/progress bar.

lordneru
  • 700
  • 7
  • 19

1 Answers1

0

I found a solution.

Using AtomicInteger, like this:

 var counter = AtomicInteger(0)
 for (anItem in itemList) {

   eventsQuery.get()
        .addOnCompleteListener { task ->
            if (task.isComplete) {

                counter.incrementAndGet()
                emitter.onNext(myItemFromTask)

                if(counter == itemList.size){
                      emitter.onComplete()
                }
            }
       }
}

If anyone find a better or more elegant solution, it would be appreciated!

lordneru
  • 700
  • 7
  • 19