The class Flow provides methods for executing a list of asynchronous tasks in parallel or sequentially or to execute a single task repeatedly as long as certain conditions are met.
// datetime format is "2022-03-31T11:03:39.348365+02:00"Task<FlowContext> currentTime = context ->fetch("https://worldtimeapi.org/api/timezone/Europe/Berlin").then(Response::json).then(json ->Promise.resolve(Js.<JsPropertyMap<String>>cast(json).get("datetime").substring(11,23))).then(context::resolve);double ms =500+newRandom().nextInt(2000);Task<FlowContext> delay = context ->newPromise<>((res, __) ->setTimeout(___ ->res.onInvoke(context), ms));// execute the two tasks in parallelFlow.parallel(newFlowContext(),List.of(currentTime, delay)).subscribe(context ->console.log("Current time: "+context.pop("n/a")));
Sequential
// datetime format is "2022-03-31T11:03:39.348365+02:00"Task<FlowContext> currentTime = context ->fetch("https://worldtimeapi.org/api/timezone/Europe/Berlin").then(Response::json).then(json ->Promise.resolve(Js.<JsPropertyMap<String>>cast(json).get("datetime").substring(11,23))).then(context::resolve);double ms =500+newRandom().nextInt(2_000);Task<FlowContext> delay = context ->newPromise<>((res, __) ->setTimeout(___ ->res.onInvoke(context), ms));// execute the two tasks in sequence and cancel after 1_000 msFlow.parallel(newFlowContext(),List.of(currentTime, delay)).timeout(1_000).subscribe(context ->console.log("Current time: "+context.pop("n/a")));
Repeated
Task<FlowContext> currentTime = context ->fetch("https://worldtimeapi.org/api/timezone/Europe/Berlin").then(Response::json).then(json ->Promise.resolve(Js.<JsPropertyMap<String>>cast(json).get("datetime").substring(11,23))).then(context::resolve);// fetch the current time until the milliseconds end with "0" and cancel after 5 iterationsFlow.repeat(newFlowContext(),currentTime).while_(context ->!context.pop("").endsWith("0")).iterations(5).subscribe(context ->console.log("Current time: "+context.pop("n/a")));
Dependency
Add the following dependency to use elemento-flow: