Hi guys , I'm trying to do a complex task in my fu...
# android
t
Hi guys , I'm trying to do a complex task in my function using coroutines. My code looks bad and my app is slow. Here is my task: 1-get the new place item that is added from database. / 2.make it selected / 3. get the last other items from database / 4. make them unselected. is there a better way to this?
Copy code
fun checkNewItemAdded(item: PlaceItem) {
    viewModelScope.launch {
        withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            val newItemAdded = async { getPlaceItem(item.id) }
            val placeItem = newItemAdded.await()
            placeItem?.let {
                    if (!it.isChecked) {
                    it.isChecked = true
                    val checkNewItem = async { update(it) }
                        checkNewItem.await()
                        val getAllPlaces = async { getPlaces() }
                        val places = getAllPlaces.await()
                        val runningTasks = places.map { place ->
                            async {
                                val singlePlaceItem = getPlaceItem(place.id)
                                place to singlePlaceItem
                            }
                        }
                        val responses = runningTasks.awaitAll()
                        responses.forEach { (place, response) ->
                            if (response != placeItem) {
                                places.find { it.id == place.id }?.isChecked = false
                                update(place)
                            }
                        }
             }
            }
       }
    }
}
z
Regarding coroutine usage, you could get rid of all
async / await
calls and just invoke all your calls manually. You only need
async
for cases where you want parallel execution, which only helps in the one case where you're then doing
awaitAll()
. Otherwise, any time you have
Copy code
val x = async { someOperation() }
val y = x.await()
You could replace it directly with
Copy code
val y = someOperation()
1
🙌 1
👍 1
For unselecting a large amount of items in the database, it'd be much better to do it all in a single database operation instead of pulling out all the data, and then performing a separate insert for each item you want to update. I don't know if you're using Room, but there you could have something like this (note that this is total pseudocode, will look different based on your actual setup and might not match your logic exactly):
Copy code
@Query("UPDATE places SET isChecked = false WHERE id != :placeId)
fun uncheckAllExcept(placeId: Long)
🙌 1
1
👍 1
t
Thank you so much Márton Braun I really appreciate your help