#completablefuture .thenapply vs .thencompose
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
it's analogous to map and flatMap in Streams
If I understans .thenapply work with the result itself ans thencompose with the result completable future but I dont see when it can be usefull
They both operate on the result
Yes I know but what thencompose avoid to do that thenapply cant do?
technically speaking nothing
var r1 = Stream.of(1, 2, 3)
.map(x -> x + 1)
.toList();
var r2 = Stream.of(1, 2, 3)
.flatMap(x -> Stream.of(x + 1))
.toList();
same as with streams
flatMap can do everything map can do - you just need to wrap a result
but avoid completable futures if its an option
the whole async java world was terrible and i'm glad it will likely die
In what case its usefull so ?
i mean, if you have a function like String::toUpperCase its annoying to have to do s -> Stream.of(s.toUppercase())
especially when you don't have the possibility of there actually being more than one element
so map vs flatMap comes down to "use map if you don't need flatMap"
very similar for .thenApply and .thenCompose
just if you have a function that works on String -> String instead of String -> CompletableFuture<String>, go with .thenApply
otherwise .thenCompose
Could you give a concret example where its better to use thencompose ?
uhh okay
1 sec
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
public class Main {
static CompletableFuture<Integer> lookupAge(String name) {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(Duration.ofMillis(1000));
return 8;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
public static void main(String[] args) {
CompletableFuture<String> name = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(Duration.ofMillis(1000));
return "bob";
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
CompletableFuture<Integer> age
= name.thenCompose(Main::lookupAge);
}
}
something like this
pretend all the thread sleeps are network calls
but truly you should avoid this whole mechanism if you can
If I understand the interst here is that you can treat age as completable future and not just a simple value ?
Finally I think I understand thencompose its just a way to work with embeded future but its madable with thenapply