Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle an interface with suspend that returns a JS friendly type #34

Merged
merged 1 commit into from
Feb 2, 2023

Conversation

shama
Copy link
Contributor

@shama shama commented Feb 2, 2023

If we have an interface that contains a suspend that returns a type that would get converted back and forth for JS (Long <-> Double), I noticed it tries to cast the type (.toLong()) before the promise is awaited.

An example:

@KustomExport
interface Thing {
    suspend fun getThing(): Long
}

class NonJSThing : Thing {
    override suspend fun getThing(): Long {
        return 1
    }
}

@KustomExport
class JSThing : Thing {
    override suspend fun getThing(): Long {
        return 1
    }
}

would generate the following code:

private class ImportedThing(
    internal val exported: Thing,
) : CommonThing {
    public override suspend fun getThing(): Long {
        val abortController = AbortController()
        val abortSignal = abortController.signal
        coroutineContext.job.invokeOnCompletion { abortController.abort() }
        val result = exported.getThing(    abortSignal = abortSignal)
        // It is casting the result to long before the promise has been awaited
        return result.toLong().await()
    }
}

with this change it now generates:

private class ImportedThing(
    internal val exported: Thing,
) : CommonThing {
    public override suspend fun getThing(): Long {
        val abortController = AbortController()
        val abortSignal = abortController.signal
        coroutineContext.job.invokeOnCompletion { abortController.abort() }
        val result = exported.getThing(    abortSignal = abortSignal).await()
        // The result has awaited the promise to resolve and is now a Double to be casted toLong()
        return result.toLong()
    }
}

If we are KustomExporting an interface that contains a suspend that
returns a JS friendly type (e.g. Long <-> Double), we want to await
the promise result before importing the JS type back to the Kotlin
type.

> promise.toLong().await()
becomes:
> promise.await().toLong()
@glureau
Copy link
Collaborator

glureau commented Feb 2, 2023

Nice catch, thanks for your contribution!

@glureau glureau merged commit adc689c into deezer:master Feb 2, 2023
@shama shama deleted the interface-with-suspend branch February 2, 2023 16:33
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.

None yet

2 participants