wrschneider
wrschneider

Reputation: 18770

Workaround for lack of generators/yield keyword in Groovy

Wondering if there is a way I can use sql.eachRow like a generator, to use it in a DSL context where a Collection or Iterator is expected. The use case I'm trying to go for is streaming JSON generation - what I'm trying to do is something like:

def generator = { sql.eachRow { yield it } }
jsonBuilder.root {
  status "OK"
  rows generator()
}

Upvotes: 9

Views: 3952

Answers (1)

blackdrag
blackdrag

Reputation: 6508

You would need continuation support (or similiar) for this to work to some extend. Groovy does not have continuations, the JVM also not. Normally continuation passing style works, but then the method eachRow would have to support that, which it of course does not. So the only way I see is a makeshift solution using threads or something like that. So maybe something like that would work for you:

def sync = new java.util.concurrent.SynchronousQueue()
Thread.start { sql.eachRow { sync.put(it) } }
jsonBuilder.root {
  status "OK"
  rows sync.take()
}

I am not stating, that this is a good solution, just a random consumer-producer-work-around for your problem.

Upvotes: 3

Related Questions