Is there a way to use synchronized() with coroutin...
# coroutines
a
Is there a way to use synchronized() with coroutines? I have a need for several short running coroutines/threads to synchronize access to another function that gets data. Synchronization is needed since the first call is over http then cached locally, to prevent redundant web requests.
z
Copy code
import kotlinx.coroutines.sync.Mutex

private val lock = Mutex()
…
lock.withLock {
  // critical section
}
a
Thanks, will give that a try
t
You could load the required data with
async
, then keep the resulting
Deferred
. The result of the HTTP call will be cached for next function calls, requiring no synchronization
k
No the issue is when 2 calls happen at nearly the same time.
You could also use actors.