SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import kotlinx.coroutines.*
  2.  
  3. // this will execute on background thread
  4. suspend fun getDataFromDatabase() : Array<Int> = withContext(Dispatchers.IO) {
  5.     delay(1000)
  6.     println("Thread name inside context: ${Thread.currentThread().name}")
  7.     Array(10) { i -> i }
  8. }
  9.  
  10. fun main(args : Array<String>) = runBlocking {
  11.  
  12.     // CoroutineScope is like a handle that you can use to control your coroutines
  13.     // As far as I understand, related coroutines should be launched from the same scope.
  14.     // If one of them fails, all other will be canceled (unless you're using supervisorscope)
  15.  
  16.     val coroutineScope = this
  17.  
  18.     // On android you would use Dispatchers.Main for android UI thread
  19.     // val coroutineScope = CoroutineScope(Dispatchers.Main)
  20.  
  21.     var jobNames = arrayOf<Int>()
  22.  
  23.     // will launch on main thread
  24.     val job = coroutineScope.launch {
  25.  
  26.         jobNames = getDataFromDatabase()
  27.  
  28.         // this will be scheduled to execute on the main thread (meaning it can make changes on the UI)
  29.         println(jobNames.joinToString(prefix = "[", postfix = "]"))
  30.  
  31.         println("Thread name inside coroutine: ${Thread.currentThread().name}")
  32.     }
  33.  
  34.     // count will be zero
  35.     var count = jobNames.size
  36.  
  37.     // Will not execute
  38.     for (i in 1..count) {
  39.         println("count inside loop: $count")
  40.     }
  41.  
  42.     // count will still be zero
  43.     println("count outside loop: $count")
  44.  
  45.     job.join()
  46.  
  47.     count = jobNames.size;
  48.     println("Count again: $count")
  49.     println("Thread name on main function: ${Thread.currentThread().name}")
  50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top