Hello guys! So I have this component that is in ch...
# coroutines
r
Hello guys! So I have this component that is in charge of syncing some remote config. We also have a use case that lets our users force this synchronisation to happen, and, in that case, I want the component to respond with the result of that syncing request. The thing is that I want to make it so the actual syncing is non cancellable (not by cancelling the job that calls
forceSync
) but the "waiting on the result" part should be. This is what I have now:
Copy code
suspend fun forceSync(): Result<Unit, Error> {
    return deferredForceSyncNow().await()
}

private fun deferredForceSyncNow() = async { // this class implements CoroutineScope
    syncNow(isForceSync = true) //syncNow is another suspend function that returns a Result<Config, Error>
        .map { /* Unit */ }
}
So the idea here is I made the
deferredForceSyncNow
return a Deferred object right away and then if the
forceSync
is called on a job that gets cancelled, the
await
is what gets cancelled, not the actual "syncing". I am wondering though, is this the best we can do? And does it work as I expect it to? I found it a little weird, but it looks alright so far 🤔
s
The basic approach here seems right 👍. By saying that you want the
forceSync()
function to be cancelable without actually canceling the sync job, you're basically saying that the function that calls
forceSync()
is not the owner of the sync job. That means the sync job needs a separate owner, which is the coroutine scope belonging to the class.
In effect the semantics you're describing are those of a join, where the
forceSync()
function joins the sync task in a cancelable way. An
await()
is just a
join()
that returns a result, so it fits well here.
👍 1
r
alright thank you 🙏