Last active
April 4, 2018 05:54
-
-
Save adamw/676e3922ae3c1390f18327ecb9664394 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package test; | |
| import java.util.concurrent.CompletableFuture; | |
| public class Compare4Wrappers { | |
| // data structures | |
| public class ProfileData { | |
| public long getUserId() { return 42; } | |
| } | |
| public class User { | |
| public String getEmail() { return null; } | |
| boolean getNotificationsEnabled() { return false; } | |
| } | |
| // I/O operations: non-blocking, asynchronous | |
| <T> CompletableFuture<T> fetchFromDb(Class<T> entityClass, long id) { return null; } | |
| CompletableFuture<Void> sendEmail(String to, String content) { return null; } | |
| CompletableFuture<Void> sendHttpPost(String url, Object payload) { return null; } | |
| // the business logic: asynchronous | |
| CompletableFuture<String> runBusinessProcess(ProfileData profileData) { | |
| // thenCompose: also known as flatMap, combines two futures | |
| return fetchFromDb(User.class, 42).thenCompose(user -> { | |
| if (user != null) { | |
| // storing the intermediate results in variables | |
| CompletableFuture<Void> httpResult = sendHttpPost( | |
| "http://profile_service/post/" + profileData.getUserId(), profileData); | |
| CompletableFuture<Void> emailResult = httpResult.thenCompose(x -> { | |
| if (user.getNotificationsEnabled()) { | |
| return sendEmail(user.getEmail(), "profile updated"); | |
| } else { | |
| // thenCompose requires always to return a future - here we have | |
| // to "lift" a constant into the wrapper | |
| return CompletableFuture.completedFuture(null); | |
| } | |
| }); | |
| // x has type Void and is never used | |
| return emailResult.thenApply(x -> "ok"); | |
| } else { | |
| return CompletableFuture.completedFuture("user not found"); | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment