Is there any particular reason why `StateFlow/Muta...
# flow
a
Is there any particular reason why
StateFlow/MutableStateFlow
doesn’t implement
ReadOnlyProperty/ReadWriteProperty
? It seems like it’s a perfect fit for a thread-safe property.
t
probably because a significant number of usages of StateFlow are not properties
but there may be a good use case for making a separate class that implements ReadOnlyProperty/ReadWriteProperty using a StateFlow/MutableStateFlow
(favoring composition over inheritance)
a
You don’t actually need to implement them. Extension functions work just as well.
I was just surprised it’s not built-in, as it seems like such an obvious use, so I was wondering if I’m missing something.
e
Copy code
val stateFlow: MutableStateFlow<T> = ...
var flowValue: T by stateFlow::value
it doesn't need to be built into StateFlow specifically, the stdlib already contains all the extensions needed to make the above work
a
Sure, but I’d like to use it without declaring a separate property:
Copy code
var counter by MutableStateFlow(1)
e
Copy code
var counter by MutableStateFlow(1)::value
but why?
a
Hmm, didn’t think of that. Why? Because
StateFlow
is thread-safe
Is there a delegate specifically for thread-safety?
t
if you don’t have a separate property to store the flow, then you don’t need a flow.
The only reason you need a flow is if you need to observe it.
You can’t observe it if you never store the flow anywhere else
If your problem is needing a threadsafe property, I would not use Flow for that.
e
what aspect of thread safety do you need? if it's simply observability across all threads, then a
@Volatile
field works for every type except
Long
and
Double
a
Yes, observability across threads. I don’t want to do a JVM-specific annotation, and as you said, it doesn’t work for 64-bit values.
I guess the better question is why there is no
Delegates.synchronized(…)
e
synchronization itself is not cross-platform
kotlinx.coroutines uses kotlinx.atomicfu under the hood, which does provide delegates for its atomic types
t
a
Nice, that's what I was looking for.
1