Skip to content
ryankenney edited this page Nov 8, 2015 · 2 revisions

Imagine that you want to model this logic in a java gui:

  • On User Click
    • Read User Permissions
    • If User Has "edit" Permissions
      • Prompt User for New Value
      • Store New Value
      • If Store Fails
        • Notify User of Failure
    • If User Does Not Have "edit" Permissions
      • Notify User of Permissions Issue

Because many of these actions are asynchronous (they require a server or user response before resuming), you can end up with code that looks like this:

	public void onUserClick() {
		readUserPermissions();
	}

	void readUserPermissions() {
		webServer.readUserPermissions(user, new ReturnCallback<Permissions> () {
			public void handleResult(Permissions permissions) {
				if (permissions.permissions.contains("edit")) {
					promptUserForNewValue();
				} else {
					notifyPermissionsError();
				}
			}
		});
	}

	void notifyPermissionsError() {
		userInterface.showError("User does not have edit permission");
	}

	void promptUserForNewValue() {
		userInterface.promptForNewValue(new ReturnCallback<String> () {
			@Override
			public void handleResult(String result) {
				updateStoredValue(result);
			}
		});
	}

	void updateStoredValue(String value) {
		webServer.storeValue(value, new ReturnCallback<Status> () {
			@Override
			public void handleResult(Status result) {
				if (result != Status.OK) {
					notifyStoreError();
				}
			}
		});
	}

	void notifyStoreError() {
		userInterface.showError("Store action failed");
	}

Where did that nice little block of conditional logic go? It got smeared across all of the callback methods necesssary to string the asynchronous actions together.

The jasync-driver Solution

With jasync-driver, we can define the logic block as if everything is synchronous. For example, this models the logic above:

	final JasyncDriver driver = new JasyncDriver();
	driver.execute(new DriverBody() {
		public void run() {
			Permissions permissions = driver.execute(readUserPermissions, user);
			if (!driver.execute(hasEditPermission, permissions)) {
				driver.execute(notifyPermissionsError);
			} else {
				String userInput = driver.execute(promptUserForNewValue);
				Status storeStatus = driver.execute(updateStoredValue, userInput);
				if (storeStatus != Status.OK) {
					driver.execute(notifyStoreError);
				}
			}
		}
	});

See the side panel for more information.

Clone this wiki locally