Repository navigation
Description
We need to be able to conveniently use Flow to represent an updateable state in applications. This change introduces StateFlow -- an updateable value that represents a state and is a Flow. The design is flexible to fit a variety of needs:
StateFlow<T>interface is a read-only view that gives access to the currentvalueand implements aFlow<T>to collect updates to the values.MutabaleStateFlow<T>interface adds value-modification operation.
A MutableStateFlow(x) constructor function is provided. It returns an implementation of MutableStateFlow with the given initial value. It can be exposed to the outside world as either StateFlow<T> if fast non-reactive access to the value is needed, or as Flow<T> if only reactive view of updates to the value is needed.
Core state flow API can be summarized like this:
package kotlinx.coroutines.flow
interface StateFlow<T> : Flow<T> {
val value: T // always availabe, reading it never fails
}
interface MutableStateFlow<T> : StateFlow<T> {
override var value: T // can read & write value
}
fun <T> MutableStateFlow(value: T): MutableStateFlow<T> // constructor funImplementation is available in PR #1974.
StateFlow vs ConflatedBroadcastChannel
Conceptually state flow is similar to ConflatedBroadcastChannel and is designed to completely replace ConflatedBroadcastChannel in the future. It has the following important improvements:
StateFlowis simpler because it does not have to implement all theChannelAPIs, which allows for faster, garbage-free implementation, unlikeConflatedBroadcastChannelimplementation that allocates objects on each emitted value.StateFlowalways has a value that can be safely read at any time viavalueproperty. UnlikeConflatedBroadcastChannel, there is no way to create a state flow without a value.StateFlowhas a clear separation into a read-onlyStateFlowinterface and aMutableStateFlow.StateFlowconflation is based on equality, unlike conflation inConflatedBroadcastChannelthat is based on reference identity. It is a stronger, more practical conflation policy, that avoids extra updates when data classes are emitted. You can consider it to have an embeddeddistinctUntilChangedout-of-the-box.StateFlowcannot be currently closed likeConflatedBroadcastChanneland can never represent a failure. This feature might be added in the future if enough compelling use-cases are found.
StateFlow is designed to better cover typical use-cases of keeping track of state changes in time, taking more pragmatic design choices for the sake of convenience.
Example
For example, the following class encapsulates an integer state and increments its value on each call to inc:
class CounterModel {
private val _counter = MutableStateFlow(0) // private mutable state flow
val counter: StateFlow<Int> get() = _counter // publicly exposed as read-only state flow
fun inc() {
_counter.value++ // convenient state update
}
}Experimental status
The initial version of this design is going to be introduced under @ExperimentalCoroutinesApi, but it is highly unlikely that the core of the design as described above, is going to change. It is expected to be stabilized quite fast.
There are also some future possible enhancements (see below) that are not provided at this moment.
Possible future enhancement: Closing state flow
A state flow could be optionally closed in a similar way to channels. When state flow is closed all its collectors complete normally or with the specified exception. Closing a state flow transitions it to the terminal state. Once the state flow is closed its value cannot be changed. The most recent value of the closed state flow is still available via value property. Closing a state is appropriate in situations where the source of the state updates is permanently destroyed.
To support closing there would be a MutableStateFlow.close(cause: Throwable? = null): Boolean method for the owner of the state flow to close it via its writeable reference and StateFlow.isClosed: Boolean property on read-only interface.
UPDATE: Turning Flow into a StateFlow
A regular Flow is cold. It does not have the concept of the last value and it only becomes active when collected. We introduce a stateIn operator to turn any Flow into a hot StateFlow in the as a part of the family of flow-sharing operators (see #2047 ). It is designed to become a replacement for broadcastIn operator. It would subsume the need of having to have a separate "state flow builder" as you can simply write flow { .... }.stateIn(scope) to launch a coroutine that emits the values according to the code in curly braces.
Activity
StateFlow implementation
Dico200 commentedon Apr 29, 2020
I like it. You mentioned users can use convenient syntax like
state.value++- does this mean the implementation will not be thread safe?Dico200 commentedon Apr 29, 2020
Perhaps a confusing question - atomicity is something that can be added as a layer around the api
if (compareAndSet(old, new)) state.value = new. But I would just like to ask what you're planning for the state machine and whether it will be threadsafe likeJob, or more light and less thread safe.elizarov commentedon Apr 29, 2020
The internal state machine is fully thread-state, but its public API is primarily designed for cases when there is a single "owner" that sequentially updates the state's value, so we don't provide operations like
compareAndSet. They would only complicate API. We don't have compelling use-cases on the table to support them and, if need, you can always use other mechanisms to coordinate updaters if you have many of them.Dico200 commentedon Apr 29, 2020
Sounds good! 🎉
zach-klippenstein commentedon Apr 29, 2020
This API looks great, really exciting!
It would be useful to have a version of
stateInthat takes an initial value and does not suspend. This would make it easy to define a "loading" or default state while waiting for a resource to spin up.Some example use cases:
This function could be implemented on top of the existing
stateInusingonStartandrunBlocking(on the JVM target) but it would be more efficient to just initialize the internalMutableStateFloweagerly.erikc5000 commentedon Apr 29, 2020
Having the
StateFlowinterface represent a read-only state flow while the constructor function with the same name is actually mutable seems like it could lead to a lot of state flows getting unintentionally exposed as mutable. Is there a reason to not useMutableStateFlowas the name of the constructor function?Otherwise, it's looking pretty good to me!
igorwojda commentedon Apr 29, 2020
I also think that we should have separate
MutableStateFlow()constructor to avoid confusion and keep things consistent (List, Map, Android LiveData all of them have Mutable equivalents)It would be good to add extension to simplify conversion from MutableStateFlow to StateFlow
JakeWharton commentedon Apr 29, 2020
That would be an "as", not a "to", but I'm opposed to that. I don't see it adding meaningful value compared to just specifying the type explicitly. It's actually more characters, not that character count provides any meaningful metric. Plus when you enable library mode (explicit types always required) it means that function wouldn't even be needed.
ZakTaccardi commentedon Apr 29, 2020
I definitely feel weird about this - what if the initial state is built asynchronously? I currently use an actor coroutine to build state.
I guess the new pattern would be:
But this leaves the
Channel<Intention>used to communicate into theStateFlow<T>disconnected, even though they are related.EDIT: the new pattern doesn't work because
stateIn(..)suspends. What is the value in that?ZakTaccardi commentedon Apr 29, 2020
Will this be configurable? Could I inject my own predicate to evaluate if two items are different?
Obviously equality is an excellent default
elizarov commentedon Apr 30, 2020
@ZakTaccardi There is no configurability for comparisons that are used to avoid sending extra state-changes in the initial release. We are trying to keep it as simple as basic
Setoperations are. Create a separate issue with use-cases for configurable behaviour, please, if you have some use-cases for it in mind.igorwojda commentedon Apr 30, 2020
Right
asStateFlow()would be better name indeedRegarding the value well - main one is ease of use - this gives us much faster code completion, more convenient usage with IDE.
When it comes to library mode we know that majority of devs are writing apps, not libraries, but still these two solution are not mutually exclusive.
39 remaining items
elizarov commentedon May 19, 2020
@AdamSHurwitz It is better to create separate issues for new proposals.
This particular desire is taken into account by the design of
SharedFlow. See #2034. UsingSharedFlowyou can have aStateFlow-like behavior without initial value and a number of other possible tweaks. Of course, withSharedFlowyou loose access to current.value, since it may be missing, but you can dosharedFlow.replayCache.lastOrNull()if you really need it and know it is there. If something is absent inSharedFlowdesign for your use-case, please comment on the open issue #2034.Zhuinden commentedon May 25, 2020
Are you sure it's not an issue that you can potentially smart-cast an "immutable" state flow into a mutable one?
Of course, that's technically true of
Listand I haven't really seen people do it, just passMutableLists around if they really want to by-pass "read-only"-ness.elizarov commentedon May 25, 2020
@Zhuinden We have quite lengthy experience with a similar design for
List/MutableListin Kotlin and it is not causing any problems to be worried about it, as far as I know.Zhuinden commentedon May 25, 2020
Okay then, that should be great 🙂
muthuraj57 commentedon May 26, 2020
Is this enhancement tracked elsewhere where I can follow? I'm trying to publish download progress and need to close the flow once the download completes so that the collector is finished.
elizarov commentedon May 26, 2020
@muthuraj57 No. We've abandoned it. On the collector side you can use
takeWhile { ... }to stop collector when download completes. See longer discussion on this decision in #2034sampaxyz commentedon Jul 14, 2020
This idea was huge good. I'm wondering if is still handled?
I'm facing an use case to send my repository states by reactive like ->(ConflatedBroadcastChannel.send(Loading), (ConflatedBroadcastChannel.send(Sucess), etc. But Conflated... is already obsolete. Any solution into channels lib?
zach-klippenstein commentedon Jul 14, 2020
StateFlowis the replacement forConflatedBroadcastChannel.sampaxyz commentedon Jul 14, 2020
Is it available for implementation already?
zach-klippenstein commentedon Jul 14, 2020
It's not stable for implementing yourself, but it is stable for use in the latest coroutines release (see the kdoc).
StateFlow implementation (Kotlin#1974)
deinlandel commentedon Jan 15, 2021
Cannot find any actual implementation of asStateFlow() in source code, despite the fact that it is mentioned in the examples. It's also not recognized by the IDE
gildor commentedon Jan 15, 2021
@deinlandel It's part of MutableStateFlow API - https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/as-state-flow.html
If you want to convert any other Flow there is an extension stateIn
deinlandel commentedon Jan 22, 2021
@gildor I indeed found this javadoc, but the problem is, I cannot locate this function in this repository's source code, and also my IDE fails to compile the code when I try to use it even with the latest kotlinx.coroutines libraries.
LouisCAD commentedon Jan 27, 2021
@deinlandel I think there's a bug in GitHub search/indexing. Here's the permalink to the implementation of
asStateFlow():kotlinx.coroutines/kotlinx-coroutines-core/common/src/flow/operators/Share.kt
Line 357 in 1b34e1c