Skip to content

[generator] Bind Kotlin suspend functions as Task-returning methods - #13583

Open
jonathanpeppers wants to merge 7 commits into
jonathanpeppers-kotlin-default-argumentsfrom
jonathanpeppers-kotlin-suspend-as-task
Open

jonathanpeppers wants to merge 7 commits into
jonathanpeppers-kotlin-default-argumentsfrom
jonathanpeppers-kotlin-suspend-as-task

Conversation

@jonathanpeppers

@jonathanpeppers jonathanpeppers commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Context: #13582

Note

This PR is stacked on #13582. Review only the commits in this layer.

Many Android libraries, such as DataStore, Room, and Paging, expose Kotlin suspend functions. On the JVM, a suspend function takes an extra kotlin.coroutines.Continuation parameter and returns Object. The binding generator emitted that JVM shape as-is, so C# code could only call it with a hand-written Continuation implementation.

Bindings now also get an *Async method that returns a Task. The existing method does not change.

Kotlin and C# side by side

Kotlin libraryC# binding (new *Async methods)
class WeatherClient {
    suspend fun temperature(city: String): Int

    suspend fun forecast(city: String): String?

    suspend fun refresh()
}
public sealed partial class WeatherClient : Java.Lang.Object {
    public Task<int> TemperatureAsync (string city,
        CancellationToken cancellationToken = default);

    public Task<string?> ForecastAsync (string city,
        CancellationToken cancellationToken = default);

    public Task RefreshAsync (
        CancellationToken cancellationToken = default);
}
val client = WeatherClient()
val t = client.temperature("Paris")
val f = client.forecast("Paris")
client.refresh()
var client = new WeatherClient ();
int t = await client.TemperatureAsync ("Paris");
string? f = await client.ForecastAsync ("Paris");
await client.RefreshAsync (cancellationToken);

The result type comes from the Kotlin metadata, not from the erased Object:

Kotlin result C# result
Unit Task
Int, Boolean, Long, … Task<int>, Task<bool>, Task<long>, …
Int? Task<int?>
String / String? Task<string> / Task<string?>
A bound class, such as Preferences Task<Preferences>
Type parameter, inline value class, or a type the binding does not generate Task<Java.Lang.Object>
Java platform type (String!) nullable, for example Task<string?>

A real example from androidx.datastore:datastore-preferences-core-jvm:

suspend fun DataStore<Preferences>.edit(transform: suspend (MutablePreferences) -> Unit): Preferences
public static Task<Preferences> EditAsync (IDataStore obj, IFunction2 transform, CancellationToken cancellationToken = default);

Generated binding

The generator keeps the existing Continuation-based method and adds a wrapper next to it. This is the output for WeatherClient above (JNI method bodies omitted):

[Register ("temperature", "(Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", "")]
public global::Java.Lang.Object? Temperature (string city, global::Kotlin.Coroutines.IContinuation _completion)
{
	// unchanged JNI call
}

public global::System.Threading.Tasks.Task<int> TemperatureAsync (string city, global::System.Threading.CancellationToken cancellationToken = default)
{
	return global::Android.Runtime.KotlinCoroutines.CallSuspendFunctionAsync<int> (__continuation => Temperature (city!, global::Android.Runtime.Extensions.JavaCast<global::Kotlin.Coroutines.IContinuation> (__continuation)), cancellationToken);
}

public global::System.Threading.Tasks.Task<string?> ForecastAsync (string city, global::System.Threading.CancellationToken cancellationToken = default)
{
	return global::Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync<string?> (__continuation => Forecast (city!, global::Android.Runtime.Extensions.JavaCast<global::Kotlin.Coroutines.IContinuation> (__continuation)), cancellationToken);
}

public global::System.Threading.Tasks.Task RefreshAsync (global::System.Threading.CancellationToken cancellationToken = default)
{
	return global::Android.Runtime.KotlinCoroutines.CallNullableSuspendFunctionAsync<global::Java.Lang.Object> (__continuation => Refresh (global::Android.Runtime.Extensions.JavaCast<global::Kotlin.Coroutines.IContinuation> (__continuation)), cancellationToken);
}

Interface instance methods get the wrapper as an extension method in the existing *Extensions class. Static interface methods get it on the interface. The generator skips overrides, explicit interface implementations, methods that already use generateAsyncWrapper, and names that already exist.

Runtime: Android.Runtime.KotlinCoroutines

New public API in Mono.Android. Only generated code calls it, so it is hidden from IntelliSense, like ResourceIdManager:

[EditorBrowsable (EditorBrowsableState.Never)]
public static class KotlinCoroutines {
	public static Task<T> CallSuspendFunctionAsync<T> (Func<IJavaObject, Java.Lang.Object?> invoke, CancellationToken cancellationToken = default) where T : notnull;
	public static Task<T?> CallNullableSuspendFunctionAsync<T> (Func<IJavaObject, Java.Lang.Object?> invoke, CancellationToken cancellationToken = default);
}
  • The kotlin.coroutines.Continuation is a java.lang.reflect.Proxy with a managed InvocationHandler. Mono.Android has no build-time dependency on Kotlin, and no new package or Java source is needed. The Kotlin classes are found at run time with the app class loader.
  • When the Kotlin function returns COROUTINE_SUSPENDED, the Task completes later, when Kotlin calls resumeWith. Other return values complete it immediately. A kotlin.Result$Failure becomes the matching managed exception, for example Java.Lang.IllegalStateException.
  • The generator calls CallNullableSuspendFunctionAsync when the Kotlin result is nullable. CallSuspendFunctionAsync throws if Kotlin returns null for a non-null result. A Unit result uses CallNullableSuspendFunctionAsync<Java.Lang.Object>, because a Task<T> is also a Task.
  • Cancellation: the token always cancels the Task. When the app includes kotlinx.coroutines, the continuation context is a new kotlinx.coroutines.Job, and the token also calls Job.cancel, so cancellable Kotlin code (delay, withContext, …) stops. Without kotlinx.coroutines, the context is EmptyCoroutineContext, and the Kotlin work continues.
  • R8 keep rules for the Kotlin members that the helper finds by name are in all three default ProGuard configurations. Without them, Release builds with R8 failed with ClassNotFoundException: kotlin.coroutines.EmptyCoroutineContext.

An alternative was a separate NuGet package with a Kotlin bridge built on kotlinx.coroutines. That adds a build-time Kotlin dependency and a new package, and it requires kotlinx.coroutines in every app.

Validation

Standalone tests (bin\Debug\dotnet\dotnet test):

  • tests\Xamarin.Android.Tools.Bytecode-Tests: Passed 139, Skipped 2. Includes the new KotlinSuspendTests, which reads a Gradle-compiled SuspendFunctions.kt fixture.
  • tests\Java.Interop.Tools.JavaTypeSystem-Tests: Passed 17.
  • tests\generator-Tests: Passed 496. Includes the new KotlinSuspendTests, which runs the fixture through class-parse, the api.xml adjuster, and the generator.

Full SDK build (dotnet-local.cmd build Microsoft.Android.slnx, then -t:BuildExtraApiLevels, then -t:PackDotNet), then:

set TEST_ANDROID_JDK_PATH=D:\android-toolchain\jdk-21
dotnet-local.cmd test bin\TestDebug\net11.0\Xamarin.Android.Build.Tests.dll --filter Name=KotlinSuspendFunctionsAsTasks

Passed 1/1. The test binds androidx.datastore:datastore-preferences-core-jvm 1.2.1 with <AndroidMavenLibrary/> and checks the generated PreferencesKt.EditAsync. Version 1.3.0 requires datastore-core-jvm 1.3.0 exactly, and the newest NuGet packages are 1.2.1.1.

On-device, x86_64 API 36 emulator, CoreCLR:

  • A Gradle module with Kotlin suspend functions, bound into an app. This is the same code as the new MSBuildDeviceIntegration test KotlinSuspendTests.SuspendFunctionsAsTasks. Release with $(AndroidLinkTool)=r8 logs sum=5 greeting=Hello, Kotlin nothing=True failure=boom canceled=True. That covers an asynchronous resume, a synchronous result, a null result, a Kotlin exception, and cancellation through kotlinx.coroutines.delay. I ran this with the final code. A Debug build gave the same result on an earlier revision.
  • The real DataStore library, Release with R8, on an earlier revision (before the API rename): two PreferencesKt.EditAsync calls and one canceled edit log count=2 thread=DefaultDispatcher-worker-1 canceled=True. The transform runs on a kotlinx.coroutines Dispatchers.IO worker thread, the second edit reads the stored value, and cancellation works.

I did not run the MSBuildDeviceIntegration test through NUnit locally: on Windows, its teardown runs adb kill-server, which disconnects other users of a shared host. I built and ran the same project by hand. The test uses kotlinx-coroutines-core:1.10.2 from Maven (compile only). If the CI Maven mirror does not have it yet, seed it with eng/gradle/mirror-dependencies.ps1 -MavenArtifact.

Copilot AI balanced review requested due to automatic review settings November 16, 2026 18:46
@jonathanpeppers jonathanpeppers changed the title jonathanpeppers kotlin suspend as task [generator] Bind Kotlin suspend functions as Task-returning methods Nov 16, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

JNI peer-lifetime and generated-name collision bugs can cause runtime failures and uncompilable bindings, while the cancellation test does not verify that the Kotlin coroutine actually exits.

3 open issues
What changed in this PR

Adds Task-based bindings for Kotlin suspend functions, connecting Kotlin metadata parsing, C# binding generation, and the .NET for Android runtime.

Changes:

  • Preserves suspend-result metadata and generates *Async wrappers with optional cancellation tokens.
  • Adds a runtime continuation bridge for results, exceptions, and cancellation, plus R8 retention rules.
  • Adds bytecode, generator, binding-build, and device integration tests.
File Description
tests/​Xamarin.Android.Tools.Bytecode-Tests/​Xamarin.Android.Tools.Bytecode-Tests.csproj Embeds the suspend fixture.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​KotlinSuspendTests.cs Tests suspend-result metadata extraction.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle/​src/​main/​kotlin/​SuspendFunctions.kt Adds Kotlin suspend test cases.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle.targets Tracks the compiled fixture output.
tests/​MSBuildDeviceIntegration/​Tests/​KotlinSuspendTests.cs Exercises results, failures, and cancellation on-device with R8.
tests/​generator-Tests/​Unit-Tests/​KotlinSuspendTests.cs Checks generated Task wrappers.
tests/​generator-Tests/​Unit-Tests/​KotlinInlineClassEndToEndTests.cs Shares the fixture-loading helper.
tests/​generator-Tests/​generator-Tests.csproj Embeds the suspend fixture for generator tests.
src/​Xamarin.SourceWriter/​Models/​MethodParameterWriter.cs Supports default parameter values.
src/​Xamarin.Android.Tools.Bytecode/​XmlClassDeclarationBuilder.cs Exports suspend-result metadata to XML.
src/​Xamarin.Android.Tools.Bytecode/​Methods.cs Stores suspend-result metadata.
src/​Xamarin.Android.Tools.Bytecode/​Kotlin/​KotlinFixups.cs Recognizes suspend functions and their result types.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​BindingBuildTest.cs Checks Task wrappers for DataStore bindings.
src/​Xamarin.Android.Build.Tasks/​Resources/​proguard_xamarin.cfg Retains reflectively accessed Kotlin members.
src/​Xamarin.Android.Build.Tasks/​Resources/​proguard_typemap.cfg Adds Kotlin retention rules for typemap builds.
src/​Xamarin.Android.Build.Tasks/​Resources/​proguard_typemap_coreclr.cfg Adds Kotlin retention rules for CoreCLR builds.
src/​Mono.Android/​PublicAPI/​API-37/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-37.2/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-37.1/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-36/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-36.1/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-35/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​Mono.Android.csproj Includes the coroutine bridge.
src/​Mono.Android/​Android.Runtime/​KotlinCoroutines.cs Bridges Kotlin continuations to managed Tasks.
src/​Java.Interop.Tools.JavaTypeSystem/​Adapters/​JavaXmlApiImporter.cs Preserves suspend metadata through type processing.
src/​generator/​SourceWriters/​KotlinSuspendMethodWrapper.cs Generates Task-returning suspend wrappers.
src/​generator/​SourceWriters/​InterfaceExtensionsClass.cs Adds suspend wrappers as interface extensions.
src/​generator/​SourceWriters/​BoundInterface.cs Integrates static wrappers and extension generation.
src/​generator/​SourceWriters/​BoundClass.cs Integrates class and nested-interface wrappers.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​Method.cs Stores and clones suspend-result metadata.
src/​generator/​Java.Interop.Tools.Generator.Importers/​XmlApiImporter.cs Imports suspend-result metadata for generation.

Review effort: Balanced

jonathanpeppers and others added 6 commits November 23, 2026 10:14
…thods

class-parse records the Kotlin result type of suspend functions in
api.xml (kotlin-suspend-return-type); the JavaTypeSystem adjuster passes
it through. The generator emits an additive *Async(…, CancellationToken)
method that calls the existing Continuation-based method through the new
Android.Runtime.KotlinCoroutines helper.

KotlinCoroutines creates the Continuation with java.lang.reflect.Proxy,
so Mono.Android has no build-time Kotlin dependency. When
kotlinx.coroutines is present, a Job is the coroutine context and the
CancellationToken cancels it.

Co-authored-by: Copilot App <[email protected]>
…; add device test

* Java.Lang.Throwable is not a Java.Lang.Object: cancel the Job with a
  null cause, and convert the Result.Failure exception by peer reference.
* Add R8 keep rules for the Kotlin members that KotlinCoroutines finds by
  name, in all three default ProGuard configurations.
* Add an MSBuildDeviceIntegration test that binds a Gradle module with
  Kotlin suspend functions and awaits the generated *Async methods.

Co-authored-by: Copilot App <[email protected]>
* Always cancel the Task when the token is canceled; with kotlinx, also
  cancel the Job. Not all suspend functions observe the Job.
* Unregister (not Dispose) the token registration, so completion never
  waits for a running cancellation callback.
* Treat a missing kotlinx Job member like a missing kotlinx.
* Result types: skip inline classes (boxed here) and invalid or
  non-public types.
* Skip methods with an explicit interface; don't emit empty interface
  extension classes for static-only suspend methods.
* Add MethodParameterWriter.DefaultValue instead of a custom writer.
* Tests: drop a duplicate XML test; run the device test once, in
  Release with R8, which covers the keep rules.

Co-authored-by: Copilot App <[email protected]>
…sk methods

datastore-preferences-core-jvm has real Kotlin suspend APIs. The test
binds it with <AndroidMavenLibrary> and checks that PreferencesKt.edit
gets a Task-returning EditAsync method. Version 1.2.1 matches the
published NuGet packages for its dependencies.

Co-authored-by: Copilot App <[email protected]>
…findings

KotlinCoroutines.InvokeAsync<T> hid a nullability mismatch with
#pragma warning disable CS8603: JavaConvert.FromJavaObject<T> returns
T?, and C# cannot tell string from string? at run time. Split the API:

  * InvokeAsync<T> where T : notnull returns Task<T>, and throws when
    Kotlin breaks its non-null contract.
  * InvokeNullableAsync<T> returns Task<T?>.

The generator calls InvokeNullableAsync when the Kotlin result type is
nullable, so NRT bindings now get Task<string?> for String?.

Review fixes:

  * Kotlin platform types (T!) are nullable results.
  * Generic types fall back to Java.Lang.Object.
  * Add the [RestrictTo] warning to *Async wrappers.
  * Only add interface extension classes when a wrapper is generated.
  * Keep the Result.Failure exception alive while converting it.
  * Always cancel the Task, even when Job.cancel throws.
  * Treat any kotlinx lookup failure as kotlinx not present.

Tests: run the generator test through the shared adjuster helper, and
cover a nullable primitive result.

Co-authored-by: Copilot App <[email protected]>
Only generated bindings call Android.Runtime.KotlinCoroutines, so:

  * Mark it [EditorBrowsable (EditorBrowsableState.Never)], like
    ResourceIdManager and GeneratedEnumAttribute.
  * Rename InvokeAsync<T>/InvokeNullableAsync<T> to
    CallSuspendFunctionAsync<T>/CallNullableSuspendFunctionAsync<T>,
    after the JNIEnv.Call*Method pattern.
  * Remove the non-generic InvokeAsync. A Unit result uses
    CallNullableSuspendFunctionAsync<Java.Lang.Object>, because
    Task<T> is a Task.

Co-authored-by: Copilot App <[email protected]>
@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-suspend-as-task branch from 7b2b727 to da9ba1f Compare November 23, 2026 17:21
…tlin-side cancellation

* The generated self, cancellationToken and __continuation names now
  get a '_' prefix when a Kotlin parameter already uses the name.
* The device test cancels after the coroutine suspends, and checks
  that the Kotlin code stops (a finally block sets a flag). Before,
  the test passed even if the Kotlin Job was not canceled, because
  the token always cancels the Task.

Co-authored-by: Copilot App <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants