Skip to content

Add Supplier overload to Context #12927

Description

@carl-mastrangelo

Is your feature request related to a problem?

Yes, when trying to enter a Context, the call method doesn't work well with non-throwing Callables, such as lambdas. For example:

Integer theAnswer = Context.current().fork().call(() -> 42);

To fix this, I believe adding a Supplier overload to Context would solve this, since it doesn't declare a checked exception.

Describe the solution you'd like

diff --git a/api/src/context/java/io/grpc/Context.java b/api/src/context/java/io/grpc/Context.java
index c19d2db9d..374c42b35 100644
--- a/api/src/context/java/io/grpc/Context.java
+++ b/api/src/context/java/io/grpc/Context.java
@@ -27,6 +27,7 @@ import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Supplier;
 import java.util.logging.Level;
 import java.util.logging.Logger;

@@ -554,6 +555,22 @@ public class Context {
     }
   }

+  /**
+   * Immediately supply a value from a {@link Supplier} with this context as the
+   * {@link #current} context.
+   * @param supplier {@link Supplier} to use to produce the value.
+   * @return result of supplier.
+   */
+  @CanIgnoreReturnValue
+  public <V> V supply(Supplier<V> supplier) {
+    Context previous = attach();
+    try {
+      return supplier.get();
+    } finally {
+      detach(previous);
+    }
+  }
+

Additional context

Supplier is a Java 8 class, and only present in Android 24, which appears to be above the minimum support level for gRPC Java. I checked that there are some uses of Java8 classes like Duration, and they can be desugared correctly according to the Android docs. It appears the @IgnoreJRERequirement annotation can be used to avoid the animal sniffer warnings, but that lives in the api/main source, not the api/context one. Otherwise, this GitHub issue would have been a Pull Request.

I'm creating this issue to look for help on how to proceed.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions