Binding Using CompletableFuture

The same method as the previous example can also be written with the CompletableFuture API instead:

Using CompletableFuture to Read the JSON

  1. @Controller("/people")
  2. public class PersonController {
  3. Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
  4. @Post("/saveFuture")
  5. public CompletableFuture<HttpResponse<Person>> save(@Body CompletableFuture<Person> person) {
  6. return person.thenApply(p -> {
  7. inMemoryDatastore.put(p.getFirstName(), p);
  8. return HttpResponse.created(p);
  9. }
  10. );
  11. }
  12. }

Using CompletableFuture to Read the JSON

  1. @Controller("/people")
  2. class PersonController {
  3. ConcurrentHashMap<String, Person> inMemoryDatastore = [:]
  4. @Post("/saveFuture")
  5. CompletableFuture<HttpResponse<Person>> save(@Body CompletableFuture<Person> person) {
  6. person.thenApply({ p ->
  7. inMemoryDatastore.put(p.getFirstName(), p)
  8. HttpResponse.created(p)
  9. })
  10. }
  11. }

Using CompletableFuture to Read the JSON

  1. @Controller("/people")
  2. class PersonController {
  3. internal var inMemoryDatastore: MutableMap<String, Person> = ConcurrentHashMap()
  4. @Post("/saveFuture")
  5. fun save(@Body person: CompletableFuture<Person>): CompletableFuture<HttpResponse<Person>> {
  6. return person.thenApply { p ->
  7. inMemoryDatastore[p.firstName] = p
  8. HttpResponse.created(p)
  9. }
  10. }
  11. }

The above example uses the thenApply method to achieve the same as the previous example.