# Iterating over a Flow instead of using "collect"

**URL:** <https://discuss.kotlinlang.org/t/iterating-over-a-flow-instead-of-using-collect/13443>\
**Category:** Language Design\
**Created:** [July 10, 2019, 9:11pm UTC](https://discuss.kotlinlang.org/t/iterating-over-a-flow-instead-of-using-collect/13443 "2019-07-10T21:11:22Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![fernandoraviola](https://avatars.discourse-cdn.com/v4/letter/f/df788c/32.png) [@fernandoraviola](https://discuss.kotlinlang.org/u/fernandoraviola)\
**Post date:** [July 10, 2019, 9:11pm UTC](https://discuss.kotlinlang.org/t/iterating-over-a-flow-instead-of-using-collect/13443/1 "2019-07-10T21:11:22Z")

</div>

Hey, I’m sure there’s a valid reason why `Flow` was designed this way and this might be a very newby question but I figured I’d ask anyway, I might learn something along the way.

I’ve noticed you can’t iterate over a Flow using a `for loop` the same way you can iterate over a `Channel`.  
Which means we need to write code like this when we want to return something based on the result of the `Flow`:

```auto
public suspend fun <T> Flow<T>.first(): T {
    var result: Any? = NULL
    try {
        collect { value ->
            result = value
            throw AbortFlowException()
        }
    } catch (e: AbortFlowException) {
        // Do nothing
    }

    if (result === NULL) throw NoSuchElementException("Expected at least one element")
    return result as T
}

```

There’s nothing wrong with the code above but it would look nicer if it was:

```auto
public suspend fun <T> Flow<T>.first(): T {
        if (hasNext()) {
            return next() as T
        } else {
           throw NoSuchElementException("Expected at least one element")
        }
}

```

Again, I’m only asking to learn more 🙂  
If I understand correctly this can be done with `channels`, I think of `Flow`s as “simplier” channels as they don’t require synchronization. So, in theory, iterating over them with just a simple `for loop` should be viable?

---

<div class="post-metadata">

**Author:** ![fvasco](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fvasco/32/1961_2.png) [@fvasco](https://discuss.kotlinlang.org/u/fvasco)\
**Post date:** [July 11, 2019, 12:39pm UTC](https://discuss.kotlinlang.org/t/iterating-over-a-flow-instead-of-using-collect/13443/2 "2019-07-11T12:39:07Z")

</div>

Hi @fernandoraviola,  
take a look here to learn more about `Flow`: [https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html)

> [@fernandoraviola](#):
>
> If I understand correctly this can be done with `channels` , I think of `Flow` s as “simplier” channels as they don’t require synchronization.

Your idea is right, `Flow` is the _suspending implementation_ of Reactive Stream, when a stream is subscribed (`collect`) the producer push down the stream as much data is possible (respecting the backpressure).

> [@fernandoraviola](#):
>
> So, in theory, iterating over them with just a simple `for loop` should be viable?

Much of the computation environment is obtained in `collect` invocation, it cannot change.  
Moreover the `Flow` is a “one-to-one” stream and the _iteration_ cannot left unfinished.  
The Visitor Pattern (using `collect`) ensure all constraints.

`Channel` is a more flexible data structure but requires some extra cost, you have to consider a `Channel` when a `Flow` does not fit your use case.

---

<div class="post-metadata">

**Author:** ![fernandoraviola](https://avatars.discourse-cdn.com/v4/letter/f/df788c/32.png) [@fernandoraviola](https://discuss.kotlinlang.org/u/fernandoraviola)\
**Post date:** [July 11, 2019, 7:20pm UTC](https://discuss.kotlinlang.org/t/iterating-over-a-flow-instead-of-using-collect/13443/3 "2019-07-11T19:20:42Z")

</div>

Thanks for the clarification @fvasco

I’m not sure I understand what you mean by `computation environment` but I’ll make sure to read up on the link you provided to get more context on this.

Thanks again for your time!

---

<div class="post-metadata">

**Author:** ![fvasco](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fvasco/32/1961_2.png) [@fvasco](https://discuss.kotlinlang.org/u/fvasco)\
**Post date:** [July 11, 2019, 7:34pm UTC](https://discuss.kotlinlang.org/t/iterating-over-a-flow-instead-of-using-collect/13443/4 "2019-07-11T19:34:03Z")

</div>

> [@fernandoraviola](#):
>
> computation environment

`CoroutineScope`

`Job`, `Dispatcher` and so on…
