# Flows and mutable state

**URL:** https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721
**Category:** Support
**Created:** [August 9, 2020, 5:14pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721 "2020-08-09T17:14:03Z")
**Posts on this page:** 12
**Page:** 1

<div class="post-metadata">

### Author: ![radekm](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/radekm/32/7733_2.png) [@radekm](https://discuss.kotlinlang.org/u/radekm)
#### Post date: [August 9, 2020, 5:14pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/1 "2020-08-09T17:14:03Z")

</div>

From the official documentation [Shared mutable state and concurrency](https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html) I understood that kotlin flows should not be used together with mutable variables - because they’re not thread-safe.

But looking inside the standard library source code I can see that `var`s are used with flows:

```kotlin
private inline fun <T, K> Flow<T>.distinctUntilChangedBy(
    crossinline keySelector: (T) -> K,
    crossinline areEquivalent: (old: K, new: K) -> Boolean
): Flow<T> =
    flow {
        var previousKey: Any? = NULL
        collect { value ->
            val key = keySelector(value)
            @Suppress("UNCHECKED_CAST")
            if (previousKey === NULL || !areEquivalent(previousKey as K, key)) {
                previousKey = key
                emit(value)
            }
        }
    }

```

So where is the truth? Which `Flow` functions allows me to use `var` or other not thread-safe data structures?

---

<div class="post-metadata">

### Author: ![nickallendev](https://avatars.discourse-cdn.com/v4/letter/n/cdc98d/32.png) [@nickallendev](https://discuss.kotlinlang.org/u/nickallendev)
#### Post date: [August 10, 2020, 6:22am UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/2 "2020-08-10T06:22:28Z")

</div>

That documentation starts out with “Coroutines can be executed concurrently”. Multiple coroutines running concurrently is the only scenario it’s taking about. The `var` in `distinctUntilChangedBy` is only ever accessed by one coroutine. The code that touches it all runs sequencially. `collect` processes items one at a time so the `var` is never touched by multiple threads at the same time.

---

<div class="post-metadata">

### Author: ![radekm](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/radekm/32/7733_2.png) [@radekm](https://discuss.kotlinlang.org/u/radekm)
#### Post date: [August 10, 2020, 8:54am UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/3 "2020-08-10T08:54:01Z")

</div>

And if the coroutine is resumed on different threads it won’t cause any trouble? Eg. memory barriers are inserted by compiler?

---

<div class="post-metadata">

### Author: ![kyay10](https://avatars.discourse-cdn.com/v4/letter/k/c57346/32.png) [@kyay10](https://discuss.kotlinlang.org/u/kyay10)
#### Post date: [August 10, 2020, 11:12am UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/4 "2020-08-10T11:12:31Z")

</div>

It’s still one coroutine, so there’s no race conditions there. It isn’t _shared_ mutable state. It’s mutable state that can only be accessed by one execution of code

---

<div class="post-metadata">

### Author: ![radekm](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/radekm/32/7733_2.png) [@radekm](https://discuss.kotlinlang.org/u/radekm)
#### Post date: [August 10, 2020, 1:23pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/5 "2020-08-10T13:23:45Z")

</div>

> It’s mutable state that can only be accessed by one execution of code

Yeah, but the coroutine can be still executed on different threads which could lead to problems - eg. something has to ensure that cpu caches are properly flushed to main memory - otherwise each thread could see different data.

---

<div class="post-metadata">

### Author: ![jstuyts](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/jstuyts/32/2141_2.png) [@jstuyts](https://discuss.kotlinlang.org/u/jstuyts)
#### Post date: [August 10, 2020, 2:47pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/6 "2020-08-10T14:47:43Z")

</div>

> [@radekm](#):
>
> Yeah, but the coroutine can be still executed on different threads which could lead to problems - […]

No, there won’t be any problems. The stack of a coroutine is restored on each invocation. I.e. the local variables of a coroutine are not stored in the heap, but on the stack of the current thread.

---

<div class="post-metadata">

### Author: ![radekm](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/radekm/32/7733_2.png) [@radekm](https://discuss.kotlinlang.org/u/radekm)
#### Post date: [August 10, 2020, 2:58pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/7 "2020-08-10T14:58:27Z")

</div>

> [@jstuyts](#):
>
> I.e. the local variables of a coroutine are not stored in the heap, but on the stack of the current thread.

I though that coroutine is compiled as a class and coroutine’s local variables become instance variables of that class + there is an instance variable which says at which suspension point was coroutine suspended?

---

<div class="post-metadata">

### Author: ![jstuyts](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/jstuyts/32/2141_2.png) [@jstuyts](https://discuss.kotlinlang.org/u/jstuyts)
#### Post date: [August 10, 2020, 3:09pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/8 "2020-08-10T15:09:42Z")

</div>

> [@radekm](#):
>
> I though that coroutine is compiled as a class and coroutine’s local variables become instance variables of that class + there is an instance variable which says at which suspension point was coroutine suspended?

I do not know the exact implementation details, but there is a class involved somewhere of course.

The point is that the coroutine framework takes care of thread synchronization, and you can use local variables as local variables. You do not have to worry about synchronization issues when writing a coroutine. That is what makes them powerful: they are easy to reason about.

---

<div class="post-metadata">

### Author: ![radekm](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/radekm/32/7733_2.png) [@radekm](https://discuss.kotlinlang.org/u/radekm)
#### Post date: [August 10, 2020, 3:24pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/9 "2020-08-10T15:24:02Z")

</div>

> [@jstuyts](#):
>
> and you can use local variables as local variables

That would make sense. But to be honest I would be much happier if it was somehow written in the documentation and/or explained in terms of Java memory model.

I would be thankful if somebody could add such reference.

---

<div class="post-metadata">

### Author: ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)
#### Post date: [August 10, 2020, 6:41pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/10 "2020-08-10T18:41:16Z")

</div>

You could take a look at this KEEP:

> <https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md>

Just a small warning, this was the design document for the implementation of coroutines. There might be a few minor changes to coroutines since this was written. However the basic idea of how coroutines work internally should still be the same.

---

<div class="post-metadata">

### Author: ![radekm](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/radekm/32/7733_2.png) [@radekm](https://discuss.kotlinlang.org/u/radekm)
#### Post date: [August 10, 2020, 8:45pm UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/11 "2020-08-10T20:45:59Z")

</div>

Thanks - part [Concurrency and threads](https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md#concurrency-and-threads) answers my question

It would be nice if the official tutorial/documentation ([https://kotlinlang.org/docs/reference/coroutines/basics.html](https://kotlinlang.org/docs/reference/coroutines/basics.html)) mention `var` and mutable data structures as well.

---

<div class="post-metadata">

### Author: ![elizarov](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/elizarov/32/2164_2.png) [@elizarov](https://discuss.kotlinlang.org/u/elizarov)
#### Post date: [August 26, 2020, 7:35am UTC](https://discuss.kotlinlang.org/t/flows-and-mutable-state/18721/12 "2020-08-26T07:35:58Z")

</div>

You can also read this TL;DR. Hopefully that’ll dispel some common myths about concurrent access to mutable state. [What is “concurrent” access to mutable state? | by Roman Elizarov | ProAndroidDev](https://proandroiddev.com/what-is-concurrent-access-to-mutable-state-f386e5cb8292)
