Skip to content

Commit f80fbe3

Browse files
committed
Allow for CoroutineContext in invokeSuspendingFunction
This commit adds an overloaded version of invokeSuspendingFunction that specifies a CoroutineContext, instead of using Dispatchers.Unconfined. Closes gh-27193
1 parent dd3e3b2 commit f80fbe3

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

spring-core/src/main/java/org/springframework/core/CoroutinesUtils.java

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import java.util.Objects;
2222

2323
import kotlin.Unit;
24+
import kotlin.coroutines.CoroutineContext;
2425
import kotlin.jvm.JvmClassMappingKt;
2526
import kotlin.reflect.KClass;
2627
import kotlin.reflect.KClassifier;
@@ -66,17 +67,39 @@ public static <T> Deferred<T> monoToDeferred(Mono<T> source) {
6667
(scope, continuation) -> MonoKt.awaitSingleOrNull(source, continuation));
6768
}
6869

70+
/**
71+
* Invoke a suspending function and converts it to {@link Mono} or
72+
* {@link Flux}. Uses an {@linkplain Dispatchers#getUnconfined() unconfined}
73+
* dispatcher.
74+
* @param method the suspending function to invoke
75+
* @param target the target to invoke {@code method} on
76+
* @param args the function arguments
77+
* @return the method invocation result as reactive stream
78+
*/
79+
public static Publisher<?> invokeSuspendingFunction(Method method, Object target,
80+
Object... args) {
81+
return invokeSuspendingFunction(Dispatchers.getUnconfined(), method, target, args);
82+
}
83+
6984
/**
7085
* Invoke a suspending function and converts it to {@link Mono} or
7186
* {@link Flux}.
87+
* @param context the coroutine context to use
88+
* @param method the suspending function to invoke
89+
* @param target the target to invoke {@code method} on
90+
* @param args the function arguments
91+
* @return the method invocation result as reactive stream
92+
* @since 6.0
7293
*/
7394
@SuppressWarnings("deprecation")
74-
public static Publisher<?> invokeSuspendingFunction(Method method, Object target, Object... args) {
95+
public static Publisher<?> invokeSuspendingFunction(CoroutineContext context, Method method, Object target,
96+
Object... args) {
97+
7598
KFunction<?> function = Objects.requireNonNull(ReflectJvmMapping.getKotlinFunction(method));
7699
if (method.isAccessible() && !KCallablesJvm.isAccessible(function)) {
77100
KCallablesJvm.setAccessible(function, true);
78101
}
79-
Mono<Object> mono = MonoKt.mono(Dispatchers.getUnconfined(), (scope, continuation) ->
102+
Mono<Object> mono = MonoKt.mono(context, (scope, continuation) ->
80103
KCallables.callSuspend(function, getSuspendedFunctionArgs(target, args), continuation))
81104
.filter(result -> !Objects.equals(result, Unit.INSTANCE))
82105
.onErrorMap(InvocationTargetException.class, InvocationTargetException::getTargetException);

0 commit comments

Comments
 (0)