Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import kotlinx.coroutines.*
- // this will execute on background thread
- suspend fun getDataFromDatabase() : Array<Int> = withContext(Dispatchers.IO) {
- delay(1000)
- println("Thread name inside context: ${Thread.currentThread().name}")
- Array(10) { i -> i }
- }
- fun main(args : Array<String>) = runBlocking {
- // CoroutineScope is like a handle that you can use to control your coroutines
- // As far as I understand, related coroutines should be launched from the same scope.
- // If one of them fails, all other will be canceled (unless you're using supervisorscope)
- val coroutineScope = this
- // On android you would use Dispatchers.Main for android UI thread
- // val coroutineScope = CoroutineScope(Dispatchers.Main)
- var jobNames = arrayOf<Int>()
- // will launch on main thread
- val job = coroutineScope.launch {
- jobNames = getDataFromDatabase()
- // this will be scheduled to execute on the main thread (meaning it can make changes on the UI)
- println(jobNames.joinToString(prefix = "[", postfix = "]"))
- println("Thread name inside coroutine: ${Thread.currentThread().name}")
- }
- // count will be zero
- var count = jobNames.size
- // Will not execute
- for (i in 1..count) {
- println("count inside loop: $count")
- }
- // count will still be zero
- println("count outside loop: $count")
- job.join()
- count = jobNames.size;
- println("Count again: $count")
- println("Thread name on main function: ${Thread.currentThread().name}")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement