rickclephas / KMP-NativeCoroutines

Library to use Kotlin Coroutines from Swift code in KMP apps
MIT License
1.07k stars 32 forks source link

1.0.0-ALPHA-8: issues with Kotlin interfaces #110

Closed matteinn closed 1 year ago

matteinn commented 1 year ago

Hi there! With 1.0.0-ALPHA-8 (7 as well, I haven't tried other alpha versions) I can't get generated code from Kotlin interfaces with properties/functions marked with the @NativeCoroutines/@NativeCoroutinesState annotations.

To give you a concrete example it's enough to apply one small change to the RandomLettersGenerator.kt file in the sample project available in this repo.

RandomLettersGenerator will be backed by an interface, this also implies moving the annotation to the interface, as follows:

interface IRandomLettersGenerator {
    @NativeCoroutines
    suspend fun getRandomLetters(throwException: Boolean): String
}

object RandomLettersGenerator: IRandomLettersGenerator {

    override suspend fun getRandomLetters(throwException: Boolean): String {
        delay(2.seconds)
        if (throwException) {
            throw RuntimeException("the best exception ever")
        }
        val chars = mutableListOf<Char>()
        repeat(5) {
            chars.add(Random.nextInt(65, 91).toChar())
        }
        return chars.joinToString("")
    }
}

Now its usage in RandomLettersAsyncViewModel will throw an error: Screenshot 2023-05-03 at 14 49 49

Is there a way to circumvent this problem?

Many thanks!

rickclephas commented 1 year ago

Hi, thanks for reminding me! 😇

This is an unfortunate side-effect when using KSP. Objective-C doesn't support extensions on protocols, which is why you can't use them as you normally would expect. The good news is that Swift does support extensions on interfaces so with a little extra code you can actually get this syntax working.

More details and the mentioned workaround are here: https://github.com/rickclephas/KMP-NativeCoroutines/issues/103#issuecomment-1501096118.

I still need to update the README to document the limitations 😅.

matteinn commented 1 year ago

Thank you Rick, that's an effective workaround indeed! I'll close this issue!