I have a large sequence that is lazily generated, and is far too big to fit in memory.
I would like to process this sequence using coroutines to improve performance, in this example I am using 10 parallel threads for processing.
runBlocking(Dispatchers.IO.limitedParallelism(10)) {
massiveLazySequenceOfThings.forEach { myThingToProcess ->
print("I am processing $myThingToProcess")
launch() {
process(myThingToProcess)
}
}
}
The problem here is that the first print statement will be executed for EVERY item in the sequence, so for extremely large sequences like mine, this will cause OOM.
Is there no way to make the iteration of my sequence "lazy" in this example, so that only a fixed number are being processed at any one time?
Am I forced to use channels here (possibly with a buffered channel?) to force a blocking call during my sequence iteration until some items are processed? Or is there some other cleaner solution that I am missing.
In my actualt example, I am also using a supervisorScope to monitor each processing job, so If possible I would like to preserve that as well.