ursus
01/07/2021, 1:30 AMprivate val state = MutableStateFlow(IDLE)
fun doSomething() {
if (state.value == LOADING) return
state.value = LOADING
scope.launch {
try {
actuallyDoSomething()
state.value = SUCCESS
} catch(ex: Exception) {
state.value = ERROR
}
}
}
i.e. this is not guaranteed to be only single execution, right? I need to make reading & writing of LOADING synchronized, correct?gildor
01/07/2021, 3:53 AMgildor
01/07/2021, 3:53 AMgildor
01/07/2021, 3:54 AMgildor
01/07/2021, 3:55 AMgildor
01/07/2021, 3:56 AMgildor
01/07/2021, 3:57 AMursus
01/07/2021, 4:14 AMcompareAndSet
if I need the first param to be a negation (since its a enum)?
i.e. state.compareAndSet(expected = NOT Loading, new = Loading)
basically to emulate this
synchonized(state) {
if (state.value != LOADING) {
state.value = LOADING
...
}
}
Do I need to write my own primitive with the usual neverending loop etc?gildor
01/07/2021, 7:16 AMgildor
01/07/2021, 7:17 AMursus
01/10/2021, 4:46 PMursus
01/10/2021, 4:47 PMfun <T> MutableStateFlow<T>.compareNotAndSet(compareNot: T, new: T) {
do {
val value = value
if (value == compareNot) break
} while (!compareAndSet(value, new))
}
came up with this, but im not super sure if its correct
I was searching for AtomicReference, but they also only have compareAndSet, which sets if the value is the same -- which I have no idea how is that useful, but nevermindursus
01/10/2021, 5:17 PMfun <T> MutableStateFlow<T>.setIfNotEqual(newValue: T): Boolean {
synchronized(this) {
if (value != newValue) {
value = newValue
return true
} else {
return false
}
}
}
Which my non-CAS brain reads more easily