'How atomic update is implemented in Coroutines
Here's update function from Coroutines StateFlow. I have two questions:
- How is it atomic? We have multiple operations inside, how can atomicity be guaranteed without mutual exclusion?
- Why is it in while(true) loop? At what condition the loop is necessary?
- Can the loop be endless?
/**
* Updates the [MutableStateFlow.value] atomically using the specified [function] of its value.
*
* [function] may be evaluated multiple times, if [value] is being concurrently updated.
*/
public inline fun <T> MutableStateFlow<T>.update(function: (T) -> T) {
while (true) {
val prevValue = value
val nextValue = function(prevValue)
if (compareAndSet(prevValue, nextValue)) {
return
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
