Skip to content

Instantly share code, notes, and snippets.

@rocky-jaiswal
Created January 24, 2024 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rocky-jaiswal/99bb21a5c9e40693da40c27d6a8ae278 to your computer and use it in GitHub Desktop.
Save rocky-jaiswal/99bb21a5c9e40693da40c27d6a8ae278 to your computer and use it in GitHub Desktop.
Sample workflow using vavr
package dev.rockyj;
import io.vavr.API;
import io.vavr.control.Either;
import static io.vavr.API.*;
enum PossibleWorkflowStates {
INIT,
IN_PROGRESS,
PD_ACCEPT,
PD_REJECT,
MM1_SUCCESS,
UPDATE_STATUS_SUCCESS,
UPDATE_STATUS_FAILED,
NOTIFICATION_SUCCESS,
NOTIFICATION_FAILED
}
enum ErrorStates {
PD_ERROR,
MM1_FAIL,
}
@FunctionalInterface
interface StateModifier {
Either<ErrorStates, WorkflowState> execute(WorkflowState state);
}
@FunctionalInterface
interface ErrorHandler {
void execute(ErrorStates errorState);
}
record WorkflowState(PossibleWorkflowStates currentState){} // can be class as well
public class Workflow {
public static void main(String[] args) {
StateModifier insertRecordInDB = (WorkflowState state) -> {
// do work here
System.out.println("insert record in DB...");
var newState = new WorkflowState(PossibleWorkflowStates.IN_PROGRESS);
return Either.right(newState);
};
StateModifier callPDE = (WorkflowState state) -> {
// do work here
System.out.println("make PDE call...");
var newState = new WorkflowState(PossibleWorkflowStates.PD_ACCEPT);
return Either.right(newState);
// return Either.left(ErrorStates.PD_ERROR);
};
StateModifier moveMoney1 = (WorkflowState state) -> {
// do work here
System.out.println("make MM1 call...");
var newState = new WorkflowState(PossibleWorkflowStates.MM1_SUCCESS);
return Either.right(newState);
// return Either.left(ErrorStates.MM1_FAIL);
};
ErrorHandler handleFailure = (ErrorStates errorState) -> {
System.out.println(errorState);
System.out.println("handling failure ...");
};
// start
System.out.println("here we go...");
var initialState = new WorkflowState(PossibleWorkflowStates.INIT);
var finalState = insertRecordInDB
.execute(initialState)
.flatMap(state -> callPDE.execute(state))
.flatMap(state -> moveMoney1.execute(state));
// handle error states
if(finalState.isLeft()) {
API.Match(finalState.getLeft()).of(
Case($(ErrorStates.PD_ERROR), (errorState) -> run(() -> handleFailure.execute(errorState))),
Case($(ErrorStates.MM1_FAIL), (errorState) -> run(() -> handleFailure.execute(errorState)))
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment