From 98fae535e7f1f44e429457657ab82048c2a0fca0 Mon Sep 17 00:00:00 2001 From: JFronny Date: Sat, 13 Apr 2024 13:23:04 +0200 Subject: [PATCH] feat(commons): utility interface for attaching instances of an object to contexts --- .../commons/concurrent/WithScopedValue.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 commons/src/main/java/io/gitlab/jfronny/commons/concurrent/WithScopedValue.java diff --git a/commons/src/main/java/io/gitlab/jfronny/commons/concurrent/WithScopedValue.java b/commons/src/main/java/io/gitlab/jfronny/commons/concurrent/WithScopedValue.java new file mode 100644 index 0000000..d4dc3e3 --- /dev/null +++ b/commons/src/main/java/io/gitlab/jfronny/commons/concurrent/WithScopedValue.java @@ -0,0 +1,25 @@ +package io.gitlab.jfronny.commons.concurrent; + +import io.gitlab.jfronny.commons.throwable.Assume; + +public interface WithScopedValue { + ScopedValue getAttached(); + T self(); + + default void withContext(Action action) throws TEx1, TEx2 { + Assume.reintroduce(); + Assume.reintroduce(() -> ScopedValue.runWhere(getAttached(), self(), Assume.isSafe(action::run))); + } + default T withContext(Returnable action) throws TEx1, TEx2 { + Assume.reintroduce(); + return Assume.reintroduce(() -> ScopedValue.getWhere(getAttached(), self(), Assume.isSafe(action::run))); + } + + interface Returnable { + T run() throws TEx1, TEx2; + } + + interface Action { + void run() throws TEx1, TEx2; + } +}