Skip to content

Provide a collectIndexed terminal operator #1247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jcornaz opened this issue Jun 4, 2019 · 5 comments
Closed

Provide a collectIndexed terminal operator #1247

jcornaz opened this issue Jun 4, 2019 · 5 comments
Labels

Comments

@jcornaz
Copy link
Contributor

jcornaz commented Jun 4, 2019

Hi,

Like with collections and sequences we occasionally need to iterate and maintain an index like this:

var index = 0
values.collect {
  // do something with the value, knowing its index.
  ++index
}

Since forEachIndexed already exists for Iterable and Sequence and consumeEachIndexed exists for ReceiveChannel it would seem natural to me that flows provide a collectIndexed terminal operator.

@qwwdfsad qwwdfsad added the flow label Jun 4, 2019
@fvasco
Copy link
Contributor

fvasco commented Jun 4, 2019

Hi @jcornaz
what do you think about something like fun <T> Flow<T>.toIndexed(): Flow<IndexedValue<T>>?

@jcornaz
Copy link
Contributor Author

jcornaz commented Jun 4, 2019

Hi @fvasco

what do you think about something like fun Flow.toIndexed(): Flow<IndexedValue>?

Why not. except I'd call it withIndex() for consistency with the collection API.

But I think I prefer collectIndexed. I find it more natural to find, and it does not need to wrap each value (which may create unnecessary GC pressure when dealing with a lot of values).

@fvasco
Copy link
Contributor

fvasco commented Jun 4, 2019

@jcornaz

I'd call it withIndex()

I agree.

it does not need to wrap each value

In escape analisys we hope

@elizarov
Copy link
Contributor

elizarov commented Jun 5, 2019

@jcornaz When you say "we occasionally need" can you provide a slightly more concrete example where this might be needed when you work with flows, please. E.g. if you had recently run into this need in your project, you can explain what was the problem you were solving.

@jcornaz
Copy link
Contributor Author

jcornaz commented Jun 6, 2019

can you provide a slightly more concrete example where this might be needed when you work with flows, please.

Last time I felt the need for it, it was to monitor progress. Here is how it'd look like:

lines.collectIndexed { index, line ->
  processLine(line)
  println("${index + 1} lines processed")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants