Asynchrone Programmierung mit Java, thenCombine and thenCompose

in deutsch •  last year 

Mit thenCombine und thenCompose lassen sich zwei abhängige bzw. unabhängige asynchrone Funktionen kombinieren.

import java.util.concurrent.CompletableFuture;

public class Asynchron {

    /* dummy function for dependent futures 1 */
    private CompletableFuture<String> getForName(String forname) {
        return CompletableFuture.supplyAsync(
            () -> {return forname;}
        );
    }

    /* dummy function for dependent futures 2 */
    private CompletableFuture<String> getSurName(String forname, String surname) {
        return CompletableFuture.supplyAsync(
            () -> {return forname + " " + surname;}
        );
    }

    /* add two independent futures where the results are not dependent */
    public void independentFutures(){
        CompletableFuture<String> future = getForName("Heinrich ").thenCombine(
            (getSurName("Not", "Dependent")), (x,y) -> {
                return x.concat(y);
            });
        String independend_string = future.join();
        System.out.println(independend_string);
    }

    /* add tow futures where the results are dependent */
    public void dependentFutures(){
        CompletableFuture<String> future = getForName("Heinrich ").thenCompose(
            (forname) -> {
                return getSurName(forname, "Skalitz");
            });
        String independend_string = future.join();
        System.out.println(independend_string);
    }
    
    public static void main(String[] args){
        Asynchron async = new Asynchron();
        async.independentFutures();
        async.dependentFutures();
    }
}

java_async4.png


Posted from https://blurtlatam.intinte.org

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!