https://kotlinlang.org logo
#flow
Title
# flow
a

Alexander Maryanovsky

02/16/2022, 10:44 AM
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

Tim Oltjenbruns

02/16/2022, 3:04 PM
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

Alexander Maryanovsky

02/16/2022, 3:33 PM
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

ephemient

02/17/2022, 12:53 AM
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

Alexander Maryanovsky

02/17/2022, 5:17 AM
Sure, but I’d like to use it without declaring a separate property:
Copy code
var counter by MutableStateFlow(1)
e

ephemient

02/17/2022, 5:37 AM
Copy code
var counter by MutableStateFlow(1)::value
but why?
a

Alexander Maryanovsky

02/17/2022, 6:38 AM
Hmm, didn’t think of that. Why? Because
StateFlow
is thread-safe
Is there a delegate specifically for thread-safety?
t

Tim Oltjenbruns

02/17/2022, 2:57 PM
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

ephemient

02/17/2022, 3:00 PM
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

Alexander Maryanovsky

02/18/2022, 7:09 AM
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

ephemient

02/18/2022, 7:19 AM
synchronization itself is not cross-platform
kotlinx.coroutines uses kotlinx.atomicfu under the hood, which does provide delegates for its atomic types
t

Tim Oltjenbruns

02/18/2022, 1:32 PM
a

Alexander Maryanovsky

02/18/2022, 2:41 PM
Nice, that's what I was looking for.
1
41 Views