#completablefuture .thenapply vs .thencompose

1 messages · Page 1 of 1 (latest)

severe socket
#

Iv read a lot of explainations and examples but I dont get the difference anyone have another example?

elfin oceanBOT
#

<@&987246399047479336> please have a look, thanks.

umbral trout
#

it's analogous to map and flatMap in Streams

severe socket
umbral trout
#

They both operate on the result

severe socket
#

Yes I know but what thencompose avoid to do that thenapply cant do?

soft echo
#
        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

severe socket
soft echo
#

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

severe socket
soft echo
#

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

severe socket
severe socket
# soft echo uhh okay

Finally I think I understand thencompose its just a way to work with embeded future but its madable with thenapply