Skip to content

Introduce StateFlow #1973

Closed
Closed

Description

@elizarov

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 current value and implements a Flow<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 fun

Implementation 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:

  • StateFlow is simpler because it does not have to implement all the Channel APIs, which allows for faster, garbage-free implementation, unlike ConflatedBroadcastChannel implementation that allocates objects on each emitted value.
  • StateFlow always has a value that can be safely read at any time via value property. Unlike ConflatedBroadcastChannel, there is no way to create a state flow without a value.
  • StateFlow has a clear separation into a read-only StateFlow interface and a MutableStateFlow.
  • StateFlow conflation is based on equality, unlike conflation in ConflatedBroadcastChannel that 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 embedded distinctUntilChanged out-of-the-box.
  • StateFlow cannot be currently closed like ConflatedBroadcastChannel and 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

  1. added a commit that references this issue on Apr 29, 2020
    55db768
  2. Dico200 commented on Apr 29, 2020

    @Dico200

    I like it. You mentioned users can use convenient syntax like state.value++ - does this mean the implementation will not be thread safe?

  3. Dico200 commented on Apr 29, 2020

    @Dico200

    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 like Job, or more light and less thread safe.

  4. elizarov commented on Apr 29, 2020

    @elizarov
    ContributorAuthor

    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.

  5. Dico200 commented on Apr 29, 2020

    @Dico200

    Sounds good! 🎉

  6. zach-klippenstein commented on Apr 29, 2020

    @zach-klippenstein
    Contributor

    This API looks great, really exciting!

    It would be useful to have a version of stateIn that 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.

    fun <T> Flow<T>.stateIn(initialValue: T, scope: CoroutineScope): StateFlow<T>

    Some example use cases:

    • A streaming GRPC call that won't emit until it gets a value from the network, but you can provide a reasonable initial state locally.
    • A settings store that will emit whenever a setting is changed, but allows you to provide a default value that will be used if the setting has never been set or until it's initially loaded from disk.

    This function could be implemented on top of the existing stateIn using onStart and runBlocking (on the JVM target) but it would be more efficient to just initialize the internal MutableStateFlow eagerly.

  7. erikc5000 commented on Apr 29, 2020

    @erikc5000

    Having the StateFlow interface 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 use MutableStateFlow as the name of the constructor function?

    Otherwise, it's looking pretty good to me!

  8. igorwojda commented on Apr 29, 2020

    @igorwojda

    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

    fun <T> MutableStateFlow<T>.toStateFlow() = this as StateFlow<T>
    
    class CounterModel {
    	private val _counter = MutableStateFlow(0)
    	val counter = _counter.toStateFlow()
    }
    
  9. JakeWharton commented on Apr 29, 2020

    @JakeWharton
    Contributor

    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.

  10. ZakTaccardi commented on Apr 29, 2020

    @ZakTaccardi

    Unlike ConflatedBroadcastChannel, there is no way to create a state flow without a value.

    I definitely feel weird about this - what if the initial state is built asynchronously? I currently use an actor coroutine to build state.

    private val stateChannel = ConflatedBroadcastChannel<ProfileId?>()
    
    private val actor = actor<Intention> {
      stateChannel.send(getActiveProfileId())
      
      for (intention in channel) {
        // update state channel based on incoming intentions
      }
    }

    I guess the new pattern would be:

    val intentionsChannel = Channel<Intention>()
    val states = flow<ProfileId?> {
        emit(getActiveProfileId())
      
        for (intention in intentionsChannel) {
            // emit new state based on incoming intentions
        }
    }
      .stateIn(scope = this)

    But this leaves the Channel<Intention> used to communicate into the StateFlow<T> disconnected, even though they are related.

    EDIT: the new pattern doesn't work because stateIn(..) suspends. What is the value in that?

  11. ZakTaccardi commented on Apr 29, 2020

    @ZakTaccardi

    You can consider it to have an embedded distinctUntilChanged out-of-the-box.

    Will this be configurable? Could I inject my own predicate to evaluate if two items are different?

    Obviously equality is an excellent default

  12. elizarov commented on Apr 30, 2020

    @elizarov
    ContributorAuthor

    @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 Set operations are. Create a separate issue with use-cases for configurable behaviour, please, if you have some use-cases for it in mind.

  13. igorwojda commented on Apr 30, 2020

    @igorwojda

    Right asStateFlow() would be better name indeed

    Regarding 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.

  14. 39 remaining items

  15. elizarov commented on May 19, 2020

    @elizarov
    ContributorAuthor

    Please let me know if this is the best place for feedback on StateFlow since this issue has been closed.

    @AdamSHurwitz It is better to create separate issues for new proposals.

    It would desirable for the ability to create a MutableStateFlow with no value assigned to it similar to [MutableLiveData]

    This particular desire is taken into account by the design of SharedFlow. See #2034. Using SharedFlow you can have a StateFlow-like behavior without initial value and a number of other possible tweaks. Of course, with SharedFlow you loose access to current .value, since it may be missing, but you can do sharedFlow.replayCache.lastOrNull() if you really need it and know it is there. If something is absent in SharedFlow design for your use-case, please comment on the open issue #2034.

  16. Zhuinden commented on May 25, 2020

    @Zhuinden
     interface MutableStateFlow<T> : StateFlow<T> {
    

    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 List and I haven't really seen people do it, just pass MutableLists around if they really want to by-pass "read-only"-ness.

  17. elizarov commented on May 25, 2020

    @elizarov
    ContributorAuthor

    Are you sure it's not an issue that you can potentially smart-cast an "immutable" state flow into a mutable one?

    @Zhuinden We have quite lengthy experience with a similar design for List/MutableList in Kotlin and it is not causing any problems to be worried about it, as far as I know.

  18. Zhuinden commented on May 25, 2020

    @Zhuinden

    Okay then, that should be great 🙂

  19. muthuraj57 commented on May 26, 2020

    @muthuraj57

    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.

    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.

  20. elizarov commented on May 26, 2020

    @elizarov
    ContributorAuthor

    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.

    @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 #2034

  21. sampaxyz commented on Jul 14, 2020

    @sampaxyz

    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?

  22. zach-klippenstein commented on Jul 14, 2020

    @zach-klippenstein
    Contributor

    StateFlow is the replacement for ConflatedBroadcastChannel.

  23. sampaxyz commented on Jul 14, 2020

    @sampaxyz

    StateFlow is the replacement for ConflatedBroadcastChannel.

    Is it available for implementation already?

  24. zach-klippenstein commented on Jul 14, 2020

    @zach-klippenstein
    Contributor

    It's not stable for implementing yourself, but it is stable for use in the latest coroutines release (see the kdoc).

  25. added a commit that references this issue on Dec 28, 2020
    ca2d6dd
  26. deinlandel commented on Jan 15, 2021

    @deinlandel

    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

  27. gildor commented on Jan 15, 2021

    @gildor
    Contributor

    @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

  28. deinlandel commented on Jan 22, 2021

    @deinlandel

    @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.

  29. LouisCAD commented on Jan 27, 2021

    @LouisCAD
    Contributor

    @deinlandel I think there's a bug in GitHub search/indexing. Here's the permalink to the implementation of asStateFlow():

    public fun <T> MutableStateFlow<T>.asStateFlow(): StateFlow<T> =

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions