2650. Design Cancellable Function

Explanation

To solve this problem, we need to design a function cancellable that accepts a generator object and returns a cancel function and a promise. The function should handle cancelling the generator by throwing an error back to the generator if cancelled before completion. The generator function may yield promises that need to be resolved or rejected accordingly.

The key steps include:

  1. Execute the generator function, handling promises yielded by the generator.
  2. Implement the cancel functionality by throwing an error "Cancelled" if cancel is called before completion.
  3. Resolve or reject promises based on the generator's behavior.

The time complexity of the solution depends on the number of promises yielded and the cancel time. The space complexity is mainly determined by the number of promises and the size of the generator function.

import java.util.concurrent.*;

class Solution {
    public static Object[] cancellable(Generator generator) {
        CompletableFuture<Object> promise = new CompletableFuture<>();
        Callable<Object> task = () -> {
            try {
                Object result = generator.next(null);
                promise.complete(result);
            } catch (CancellationException e) {
                promise.completeExceptionally(new Exception("Cancelled"));
            } catch (Exception e) {
                promise.completeExceptionally(e);
            }
            return null;
        };
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Object> future = executor.submit(task);
        Runnable cancel = () -> {
            future.cancel(true);
        };
        return new Object[]{cancel, promise};
    }
}

interface Generator {
    Object next(Object value) throws Exception;
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.