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

jw

07/20/2019, 1:08 AM
Am I missing a
Mutex.withLock
pattern that supports a suspending body? Aside from just writing it myself, of course. Is there some anti-pattern or gotcha here that prevents it from being provided out-of-the-box?
z

Zach Klippenstein (he/him) [MOD]

07/20/2019, 2:20 AM
It’s inline, so it should allow suspending calls inside its body. This compiles for me:
Copy code
suspend fun foo() {
    val m = Mutex()
    m.withLock {  
      delay(1000)
    }
  }
j

jw

07/20/2019, 2:34 AM
ah. i didn't even try
i just refactored away my need for the mutex!
anyway thanks
i'm not sure i knew this was a thing we could do, but it certainly makes sense
d

Dico

07/20/2019, 7:40 AM
I was surprised when I noticed some time ago
l

louiscad

07/20/2019, 9:24 AM
That's what allows you to call suspending functions from scope functions (
also
,
apply
, etc.), and that's also why there's an
inline
keyword, not just a compiler optimization.
6 Views