https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Tristan

07/30/2021, 4:56 PM
Hello, I am trying to use Flow in an iOS project using objective-c. I am not so familiar with the iOS environment. Reading a bit some articles, I made the following code in Kotlin
Copy code
class IosDispatcher : CoroutineDispatcher() {
    override fun dispatch(context: CoroutineContext, block: Runnable) {
        dispatch_async(dispatch_get_main_queue()) { block.run() }
    }
}

actual class PrimaryScope : CoroutineScope {
    private val dispatcher = IosDispatcher()
    private val job = Job()

    override val coroutineContext: CoroutineContext
        get() = dispatcher + job
}

fun <T>observe(origin: Flow<T>, block: (T) -> Unit): PrimaryScope {
    val scope = PrimaryScope()

    origin.onEach {
        block(it)
    }.launchIn(scope)

    return scope
}
But when I do use it, I am getting the error from the screenshot. I use it like this (I tried with empty block in case it was related to a reference lost, or similar):
Copy code
[UnityKotlinCoroutineHelperKt observeOrigin: self.tokenStorage.events
                                          block:^(id result) {
                                          }];
Do you have some example I could use? Or article explaining how to achieve this? Thanks a lot for your lights.
m

mkrussel

07/30/2021, 5:26 PM
Any reason your not using the MainDispatcher from the coroutine library?
t

Tristan

07/30/2021, 7:52 PM
Because I also had errors with it. But might be related to something else. I'll bug another channel about it 😄
m

mkrussel

07/30/2021, 7:53 PM
My guess is your are noting using the
native-mt
version and accessing the dispatcher from a background thread, but not sure.
t

Tristan

07/31/2021, 2:40 AM
And you are correct!
3 Views