After database update coroutine is completed, set boolean flag

Viewed 145

I want to set a livedata boolean flag to true once the coroutine for saving data into the database is completed. My current code is as follows:

In ViewModel:

    private suspend fun updatePlace(eventId: Long, placeName: String, placeAddress: String) {
        withContext(Dispatchers.IO) {
            repository.updatePlace(placeName, placeAddress)
        }
    }

    fun savePlace(placeName: String, placeAddress: String) {
        val eventId = event.value!!.eId

        uiScope.launch {
            updatePlace(eventId, placeName, placeAddress)
        }
        //flag is currently set regardless of if the updatePlace function is completed
        _currentPlaceUpdated.value = true

    }

I've been reading about async and await for coroutine but haven't figured out how to set the value of _currentPlaceUpdated after the updatePlace() function is completed.

1 Answers

Just put the completion task after the updatePlace call.

uiScope.launch {
    updatePlace(eventId, placeName, placeAddress)
    _currentPlaceUpdated.value = true
}

withContext is similar to scope.async(Dispatchers.IO) { /* Code */ }.await() with some optimization over delivery of return value.

withContext suspends the current calling coroutine till the inside of it (block of code) completes. What launch does is launch the coroutine and let the next code execute that's why it is being called immediately.

Related