Temps : 30 min.
Diffiulté : *
L'objectif est de mettre en pratique le concept de coroutine en Kotlin :
Il s'agit d'importer la bibliothèque kotlinx dans le projet.
  
  org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.6.3
  
  
  Il s'agit de lancer un traitement simple en tâche de fond.
agua.crab, créez un nouveau fichier Kotlin, RaceRace.kt, créez une coroutine dans un main :
  
  fun main() = runBlocking { // this: CoroutineScope
      launch { // lance une coroutine et continue
          delay(1000L) // non-blocking: delais d'1 second (default time unit is ms)
          println("Arrived at the beach.") // affichage
      }
      println("Hermit crabs are going to the beach, see you there!") // coroutine principale continue alors que la précédente est en retard
  }
  
  
  
  
  import kotlinx.coroutines.delay
  import kotlinx.coroutines.launch
  import kotlinx.coroutines.runBlocking
  
  
  Il s'agit de créer une fonction coroutine via le mot clé suspend.
Race.kt, créez une fonction coroutine :
  
  suspend fun goToTheBeach() {
    delay(1000L)
    println("Arrived at the beach.")
  }
  
  
  main :
  
  fun main() = runBlocking { // this: CoroutineScope
        launch {
            goToTheBeach()
        }
        println("Hermit crabs are going to the beach, see you there!") // coroutine principale continue alors que la précédente est en retard
  }
  
  
  Il s'agit de lancer une coroutine avec le mot clé async et de traiter son résultat avec await.
main du fichier Race.kt, stocker une coroutine async dans une variable :
  
  val a = async {
    goToTheBeach()
    true
  }
  
  
  true :
  
  if (a.await()) {
    launch {
      goToTheBeach()
    }
  }
  
  
  kotlinlang.org: Coroutines basics
kotlinlang.org: Coroutines async await
Wikipédia: Coroutine