Search code examples
kotlinkotlinx.coroutineskotlin-native

How to build kotlinx.coroutines in Kotlin/Native (test version 0.23.4-native-1)


This question is a continuation of this thread: https://github.com/Kotlin/kotlinx.coroutines/issues/246#issuecomment-407023156

I am trying to use org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1 in a Kotlin/Native project targeting iOS.

build.gradle:

buildscript {
    repositories {
        mavenCentral()
        maven { url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies" }
    }

    dependencies {
        classpath 'org.jetbrains.kotlin:kotlin-native-gradle-plugin:0.8'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
    }
}

apply plugin: 'kotlin-platform-native'

repositories {
    jcenter()
    mavenCentral()
    maven { url "https://kotlin.bintray.com/kotlinx" }
}

sourceSets {
    main {
        component {
            target 'ios_arm32', 'ios_arm64', 'ios_x64'
            outputKinds = [KLIBRARY]
        }
    }
}

dependencies {
    expectedBy project(':common')
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1"
}

The kotlinx:kotlinx-coroutines-core-native dependency doesn't seem to work, as the produces build errors like:

error: unresolved reference: coroutines
import kotlinx.coroutines.experimental.*
               ^

If I manually include the artifact dependencies such as org.jetbrains.kotlinx:kotlinx-coroutines-core-native_release_ios_x64:0.10.3-native, then I get a complier exception:

exception: java.lang.IllegalStateException: Could not find "atomicfu-native"

This error persists, even if I also add org.jetbrains.kotlinx:atomicfu-native:0.10.3-native dependency.


Solution

  • Here is a list of things to check for (I have been through this, and finally made it work) :

    • Enable Gradle metadata. It's required to retrieve the coroutines dependencies. To do so, add this line in your "settings.gradle" file, after all the "include" instructions :

      enableFeaturePreview('GRADLE_METADATA')
      
    • use gradle 4.7 (newer version are incompatible with the meta data of the current coroutines library, they require something with 0.4 version and the current published one uses 0.3)

    • In the iOS module :

      implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1"
      
    • In your common module :

      implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.23.4"
      
    • If you have a js module, it may fail due to the gradle metadata feature. You can fix it by adding this before each of your "repositories" blocks (https://github.com/srs/gradle-node-plugin/issues/301)

      repositories.whenObjectAdded {
          if (it instanceof IvyArtifactRepository) {
              metadataSources {
                  artifact()
              }
          }
      }
      

    Hope this will be enough !