Autodesk / coroutineworker

Kotlin Coroutine-based workers for native
Apache License 2.0
370 stars 24 forks source link

Can´t get the result on the Main Thread #53

Closed sergiocasero closed 4 years ago

sergiocasero commented 4 years ago

Hello guys! First of all, thanks for the lib! But I don't understand how to "go back" to the main thread when I get the result from the BG task, I have something like this:

interface Repository {
    suspend fun getUser(): Either<Error, User>
}

And then, I want to use the worker like this:

CoroutineWorker.execute {
      repository.getUser().fold(
          error = { /* Update UI */ },
          success = { /* Update UI */ }
      )
}

I've tried with lot of approachs, like callbacks, or the withContext but looks like no one of them works, any help??

benasher44 commented 4 years ago

Thanks for your question and for using CoroutineWorker Sergio! You have hit upon a central problem that I believe will be improved when kotlinx.coroutines fully supports Kotlin/Native, but it's one that CoroutineWorker does not attempt to solve (at least not right now).

The short version is that each platform has a different preferred method to kick a lambda back to the main thread. In Apple-land, it's DispatchQueue.main.async(lambda). In JVM-land, you can use withContext(Dispatcher.Main, lambda) (i think). Even just with what I presented there, one method is async and the other is non-blocking but synchronous in that context.

To resolve this in your situation, I recommend defining some kind of function like this:

internal expect fun dispatchMain(lambda:() -> Unit)

Then you can have it do the preferred "get me back to main" method (on each platform) that suits your needs. Hope this helps!

sergiocasero commented 4 years ago

Thanks for the response!

Right now I'm working with the 1.3.5-native-mt described here -> https://github.com/kotlin/kotlinx.coroutines/issues/462, and looks pretty well (at least for easy tasks)

benasher44 commented 4 years ago

Ah if you're using that, then you shouldn't use CoroutineWorker. It effectively deprecates it. We're only keeping this library supported until that branch becomes part of a main kotlinx.coroutines release

benasher44 commented 4 years ago

I'm going to close this due to inactivity. For issues with the native-mt kotlinx.coroutines build, I recommend follow up in their repo. If you still have issues with CoroutineWorker, feel free to reopen or file a new issue!