Hi, I'm dealing with code refactoring from a synchronous system to an asynchronous one, using OSGi Promises. One pattern we have goes as follows:
public void handleNodeAddition(Object element, Set<Node> addedNodes) { Node node = diagram.getNode(element); if (node == null) { node = actionProvider.createNode(element, diagram); addedNodes.add(node); } actionProvider.synchronize(node); } The problem I'm facing is that *actionProvider.createNode()* now returns a Promise<Node> due to asynchronous execution. This means we can no longer just add nodes to the Set, but not only this, we have to make sure that each createNode() call from this thread happens after the previous one is resolved. Would there be a best practice for this kind of process? If I were to keep the pattern as-is but implement support for asynchronous node creation, here's how I would do it: public void handleNodeAddition(Object element, AtomicReference<Promise<Set<Node>>> addedNodes) { Promises.resolved(diagram.getNode(element)) .then(existingNode -> { Node node = existingNode.getValue(); Promise<Node> nodePromise; if (node == null) { // Using an AtomicReference so the Promise chain can be updated Promise<Set<Node>> addedNodesPromise = addedNodesPromiseRef.get(); nodePromise = addedNodesPromise // wait for previous node to be added .then(previousNodeAdded -> actionProvider.createNode(element, diagram)) .onSuccess(createdNode -> createdNode.setLocation(location)); addedNodesPromiseRef.set(createNodePromise .then(createdNode -> { addedNodesPromise.getValue().add(createdNode.getValue()); return addedNodesPromise; // still holds the Set }) ); } else { nodePromise = Promises.resolved(node); } return nodePromise; }) .onSuccess(nodeToSync -> actionProvider.synchronize(nodeToSync)); } Any and all advice is much appreciated, thank you! -Olivier Labrosse
_______________________________________________ OSGi Developer Mail List osgi-dev@mail.osgi.org https://mail.osgi.org/mailman/listinfo/osgi-dev