Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for lack of generators/yield keyword in Groovy

Tags:

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()
}
like image 706
wrschneider Avatar asked Jun 09 '15 21:06

wrschneider


1 Answers

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.

like image 143
blackdrag Avatar answered Nov 16 '22 02:11

blackdrag