thenApplye thenComposesono metodi di CompletableFuture. Usali quando intendi fare qualcosa per CompleteableFutureil risultato di con a Function.
thenApplyed thenComposeentrambi restituiscono un CompletableFuturecome risultato. Puoi concatenare più thenApplyo thenComposeinsieme. Fornire Functiona ogni chiamata, il cui risultato sarà l'ingresso alla successiva Function.
Il che Functionhai fornito a volte deve fare qualcosa in modo sincrono. Il tipo di ritorno del tuo Functiondovrebbe essere un non- Futuretipo. In questo caso dovresti usare thenApply.
CompletableFuture.completedFuture(1)
.thenApply((x)->x+1) // adding one to the result synchronously, returns int
.thenApply((y)->System.println(y)); // value of y is 1 + 1 = 2
Altre volte potresti voler eseguire l'elaborazione asincrona in questo Function. In tal caso dovresti usare thenCompose. Il tipo di ritorno del tuo Functiondovrebbe essere un file CompletionStage. Il successivo Functionnella catena otterrà il risultato di quello CompletionStagecome input, scartando così il file CompletionStage.
// addOneAsync may be implemented by using another thread, or calling a remote method
abstract CompletableFuture<Integer> addOneAsync(int input);
CompletableFuture.completedFuture(1)
.thenCompose((x)->addOneAsync(x)) // doing something asynchronous, returns CompletableFuture<Integer>
.thenApply((y)->System.println(y)); // y is an Integer, the result of CompletableFuture<Integer> above
Questa è un'idea simile a quella di Javascript Promise. Promise.thenpuò accettare una funzione che restituisce un valore o Promiseun valore. Il motivo per cui questi due metodi hanno nomi diversi in Java è dovuto alla cancellazione generica . Function<? super T,? extends U> fne Function<? super T,? extends CompletionStage<U>> fnsono considerati lo stesso tipo di Runtime - Function. Quindi thenApplye thenComposedevono essere denominati distintamente, altrimenti il compilatore Java si lamenterebbe delle firme del metodo identiche. Il risultato finale è che Javascript Promise.thenè implementato in due parti - thenApplye thenCompose- in Java.
Puoi leggere la mia altra risposta se sei anche confuso su una funzione correlata thenApplyAsync.
mapeflatMapinStream?thenApplyè ilmapedthenComposeè ilflatMapdiCompletableFuture. UsithenComposeper evitare di avereCompletableFuture<CompletableFuture<..>>.