Unresolved reference: launch

前端 未结 4 532
孤独总比滥情好
孤独总比滥情好 2021-02-05 00:58

Trying to run some examples for Kotlin coroutines, but can\'t build my project. I\'m using the latest gradle release - 4.1

Any suggestions what to check/fix?

Her

相关标签:
4条回答
  • 2021-02-05 01:31

    If you are using Coroutines 1.0+, the import is no longer

    import kotlinx.coroutines.experimental.*

    but

    import kotlinx.coroutines.launch

    You would need the following in the dependencies closure of your build.gradle (for Coroutines 1.0.1):

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1"
    
    0 讨论(0)
  • 2021-02-05 01:43

    Try this way,

    //add this lines to gradle

     implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.kotlinx_coroutines"
     implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.kotlinx_coroutines"
    
    
      class xyz{
         private val job = Job()
            private val coroutinesScope: CoroutineScope = CoroutineScope(job + Dispatchers.IO)
    
          ....
         . ...
           coroutinesScope.launch {
                           // task to do
                            Timber.d("Delete Firebase Instance ID")
                        }
    
    
        // clear the job
          job.cancel()
    
        }
    
    0 讨论(0)
  • 2021-02-05 01:44

    Launch isn't used anymore directly. The Kotlin documentation suggests using:

    fun main() { 
        GlobalScope.launch { // launch a new coroutine in background and continue
            delay(1000L)
            println("World!")
        }
        println("Hello,") // main thread continues here immediately
        runBlocking {     // but this expression blocks the main thread
            delay(2000L)  // ... while we delay for 2 seconds to keep JVM alive
        } 
    }
    
    0 讨论(0)
  • 2021-02-05 01:47

    Like already answered in the comments, the import is missing for the kotlinx.coroutines.experimental.* package. You can have a look at my examples at GitHub if you like.

    import kotlinx.coroutines.experimental.*
    
    fun main(args: Array<String>) {
    
        launch(CommonPool) {
            delay(1000)
            LOG.debug("Hello from coroutine")
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题