I’m trying to do something like this: ```val ref ...
# kotlin-native
m
I’m trying to do something like this:
Copy code
val ref = runOnBackgroundThread {
    while(threadIsAlive) {
        // do some work
        runOnUIThread {
            // refresh UI
        }
        sleep(100) // pause bg thread for 100ms
    }
}

// at some later point
ref.cancel() // stop thread
I can do it on Android and JVM using coroutines like this:
Copy code
val job = GlobalScope.async {
    while(isActive) {
        // do some work
        launch(context = Dispatchers.Main) {
            // refresh UI
        }
        delay(100)
    }
}

// later
job.cancel()
but Kotlin Native doesn’t support async coroutines yet. I tried to create my own functions that use iOS dispatchers under the hoods but I’m getting
illegal attempt to access non-shared <object>
exceptions which I don’t fully understand. Seems like this is not an easy task. The only sample I was able to find is this: https://github.com/wojtek-kalicinski/sudoku-android/blob/master/libsudoku/src/iosMain/kotlin/me/kalicinski/sudoku/Async.kt but the comments are saying that it’s a hack. Is there a sample that shows how to do it properly?
j
are you aware of Workers?
You can use Coroutines on the main thread, and use Workers for stuff on BG threads. See: https://github.com/JetBrains/kotlin-native/tree/master/samples/workers
m
Yeah I saw Workers. I’m trying to make it work right now. I have a worker that does:
Copy code
while(condition) {
  //execute instruction
  // and now I want to block this worker, execute something on main thread and resume its execution
}
Not sure how I switch for a moment to UI thread from a worker. I can jump from 1 worker to another but I’m not sure how to jump back to UI thread without finishing the worker.