groovyconcurrencyparallel-processingpoolgpars

GParse call BackendService async


I'm trying to implement asynchronism in the backend calls, I've been reading and it seems that GParse is a good library to implement this, but it's not clear to me how i can implement this in a correct way. Can anyone help me? This is my example:

    def itemsResults
    def locationResults
    def itemsNearLocation
    GParsPool.withPool {
        itemsResults = {searchMyItems()}.async().call()
        locationResults = {getLocations()}.async().call()
        itemsNearLocation = {getItemsNear(locationResults)}.async().call() // i need locationresults answer in order to call this service

    }
    model.putAll(["items": itemsResults, 
                  "itemsNearLocation":itemsNearLocation])

    return "myView"

So, i need to call 2 apis call and then in the third one i need to use one of the response called async before, and finally add this to my model. How can i achieve this?


Solution

  • You could use GPars dataflows for this... Something like this should work I believe (not tried it though):

    import groovyx.gpars.dataflow.Dataflows
    import static groovyx.gpars.dataflow.Dataflow.task
    
    final def df = new Dataflows()
    
    task {
        df.itemsResults = searchMyItems()
    }
    
    task {
        df.locationResults = getLocations()
    }
    
    task {
        df.itemsNearLocation = getItemsNear(df.locationResults)
    }
    
    def lastTask = task {
        model.putAll(["items": df.itemsResults, 
                      "itemsNearLocation":df.itemsNearLocation])
    }
    
    lastTask.join()