Home > Enterprise >  android wait for filtering finish with coroutines
android wait for filtering finish with coroutines

Time:01-05

I have the next code:

 private fun filterCarouselItems(loggedInFilter: Boolean) {

    CoroutineScope(Dispatchers.IO).launch {
        if (loggedInFilter)
            filteredCarouselItems = carouselItems.filter {
                it.visible == CarouselVisibilityEnum.LOGGEDIN.visibility
                        || it.visible == CarouselVisibilityEnum.BOTH.visibility
            } as ArrayList<CarouselItem>
        else {
            filteredCarouselItems = carouselItems.filter {
                it.visible == CarouselVisibilityEnum.LOGGEDOUT.visibility
                        || it.visible == CarouselVisibilityEnum.BOTH.visibility
            } as ArrayList<CarouselItem>
        }

        withContext(Dispachers.Main) {
        notifyDataSetChanged()
    }
    }
}

I would like my code to execute sequentially. By this, I mean that I would like that my function finishes the filtering and after that calls the notifyDataSetChanged method. What is the best way to do this by using coroutines (without blocking UI/main thread?

CodePudding user response:

Note that calling notifyDataSetChanged() from background thread has no effect.

private fun filterCarouselItems(loggedInFilter: Boolean) {
    CoroutineScope(Dispatchers.IO).launch {
        if (loggedInFilter)
            filteredCarouselItems = carouselItems.filter {
                it.visible == CarouselVisibilityEnum.LOGGEDIN.visibility
                        || it.visible == CarouselVisibilityEnum.BOTH.visibility
            } as ArrayList<CarouselItem>
        else {
            filteredCarouselItems = carouselItems.filter {
                it.visible == CarouselVisibilityEnum.LOGGEDOUT.visibility
                        || it.visible == CarouselVisibilityEnum.BOTH.visibility
            } as ArrayList<CarouselItem>
        }
        // add this line 
        withContext(Dispachers.Main) {
            notifyDataSetChanged()
        }
    }
}
  •  Tags:  
  • Related