Last active
January 6, 2017 18:22
-
-
Save hugithordarson/14f9a77d4b7d270dd6003084fdea7fb8 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
/** | |
* Maps keyPaths in this component to the methods that should supply their values (asynchronously) | |
*/ | |
private Map<String, Supplier> asyncFields = new HashMap<>(); | |
public SMFront( WOContext context ) { | |
super( context ); | |
bindAsyncField( "priceChanges", this::_priceChanges ); | |
bindAsyncField( "numberOfEntriesToday", this::_numberOfEntriesToday ); | |
bindAsyncField( "turnoverToday", this::_turnoverToday ); | |
bindAsyncField( "numberOfUsersToday", this::_numberOfUsersToday ); | |
bindAsyncField( "numberOfReceiptsToday", this::_numberOfReceiptsToday ); | |
bindAsyncField( "pieData", this::_pieData ); | |
populateAsyncFields(); | |
} | |
/** | |
* Add a [keyPath] to be populated using [supplier] before the component is rendered. | |
* | |
* @keyPath The keyPath in this WOComponent to assign the value to. | |
* @supplier The Method to invoke to create the value. | |
*/ | |
private void bindAsyncField( String keyPath, Supplier supplier ) { | |
asyncFields.put( keyPath, supplier ); | |
} | |
/** | |
* Populates all the fields in asyncFields asynchronously. | |
*/ | |
private void populateAsyncFields() { | |
try { | |
CompletableFuture[] futures = new CompletableFuture[asyncFields.size()]; | |
int i = 0; | |
for( Map.Entry<String, Supplier> entry : asyncFields.entrySet() ) { | |
futures[i++] = CompletableFuture.supplyAsync( entry.getValue() ).thenAccept( ( value ) -> { | |
takeValueForKeyPath( value, entry.getKey() ); | |
} ); | |
} | |
CompletableFuture.allOf( futures ).get(); | |
} | |
catch( InterruptedException | ExecutionException e ) { | |
throw new RuntimeException( "Failed to populate async fields", e ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment