https://kotlinlang.org logo
Title
a

Andrew

03/14/2020, 4:13 AM
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

Zach Klippenstein (he/him) [MOD]

03/14/2020, 4:30 AM
import kotlinx.coroutines.sync.Mutex

private val lock = Mutex()
…
lock.withLock {
  // critical section
}
a

Andrew

03/14/2020, 4:40 AM
Thanks, will give that a try
t

tseisel

03/14/2020, 8:37 AM
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

Kroppeb

03/14/2020, 10:47 AM
No the issue is when 2 calls happen at nearly the same time.
You could also use actors.