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
@Controller("/people")
public class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>();
@Post("/saveFuture")
public CompletableFuture<HttpResponse<Person>> save(@Body CompletableFuture<Person> person) {
return person.thenApply(p -> {
inMemoryDatastore.put(p.getFirstName(), p);
return HttpResponse.created(p);
}
);
}
}
Using CompletableFuture to Read the JSON
@Controller("/people")
class PersonController {
Map<String, Person> inMemoryDatastore = new ConcurrentHashMap<>()
@Post("/saveFuture")
CompletableFuture<HttpResponse<Person>> save(@Body CompletableFuture<Person> person) {
person.thenApply({ p ->
inMemoryDatastore.put(p.getFirstName(), p)
HttpResponse.created(p)
})
}
}
Using CompletableFuture to Read the JSON
@Controller("/people")
class PersonController {
internal var inMemoryDatastore: MutableMap<String, Person> = ConcurrentHashMap()
@Post("/saveFuture")
fun save(@Body person: CompletableFuture<Person>): CompletableFuture<HttpResponse<Person>> {
return person.thenApply { p ->
inMemoryDatastore[p.firstName] = p
HttpResponse.created(p)
}
}
}
The above example uses the thenApply
method to achieve the same as the previous example.