Issue
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?
Solution
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()
}
}
}
Answered By - Hussien Fahmy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.