Skip to content

Commit

Permalink
Handle an interface with suspend that returns a JS friendly type
Browse files Browse the repository at this point in the history
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()
  • Loading branch information
shama authored and glureau committed Feb 2, 2023
1 parent 0726ff6 commit adc689c
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,12 @@ fun FunctionDescriptor.buildWrappingFunctionBody(
body += "val result = $callStr("
body += if (parameters.isNotEmpty()) "\n" else ""
body += params
body += if (parameters.isNotEmpty()) ")\n" else ")\n"
body += if (parameters.isNotEmpty()) ")" else ")"

body += if (import && isSuspend) ".%M()\n".toFormatString(coroutinesAwait) else "\n".toFormatString()

body += if (import || !isSuspend) "return·" else ""
body += returnType.portMethod(import, "result".toFormatString())
body += if (import && isSuspend) ".%M()".toFormatString(coroutinesAwait) else "".toFormatString()

if (!import && isSuspend) body += "\n}"
return body
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package sample.coroutines

import deezer.kustomexport.KustomExport

@KustomExport
interface IThingDoer {
suspend fun doThings(): List<Long>
}

class NonWebThingDoer : IThingDoer {
override suspend fun doThings(): List<Long> {
return listOf(1, 2, 3)
}
}

@KustomExport
class WebThingDoer : IThingDoer {
override suspend fun doThings(): List<Long> {
return listOf(3, 2, 1)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { runTest } from "../shared_ts/RunTest"
import { assert, assertEquals, assertQuiet, assertEqualsQuiet } from "../shared_ts/Assert"
import { sample } from '@kustom/Samples'

runTest("InterfaceWithSuspend", async () : Promise<void> => {
var neverAbortController = new AbortController()
var neverAbortSignal = neverAbortController.signal

const thingDoer = new sample.coroutines.js.WebThingDoer()
const res = await thingDoer.doThings(neverAbortSignal)
assertEquals([3, 2, 1].join(","), res.join(","), "executes suspend function with JS friendly types")
})

0 comments on commit adc689c

Please sign in to comment.