Any advice on how to approach this problem? I want...
# flow
c
Any advice on how to approach this problem? I want to use
MutableStateFlow.compareAndSet()
, but with a `sealed interface`:
Copy code
sealed interface State {
  object NotConnected : State
  class Connected(val connection: SomeConnection) : State
}

val stateFlow = MutableStateFlow<State>(State.NotConnected)
...
// Obviously doesn't work, can't use State.Connected in this way
stateFlow.compareAndSet(State.Connected, State.NotConnected)
It seems I could solve this naively with something like (** edited to add synchronized)
Copy code
inline fun <T, reified U: T> MutableStateFlow<T>.compareAndSet(update: T): Boolean = synchronized(this) {
  val value = this.value
  return if (value is U) compareAndSet(value, update) else false
}