How can I block while a coroutine is running? My u...
# coroutines
a
How can I block while a coroutine is running? My use case is that I'm confining operations to one thread in a class which has shared mutable state so I have to use a single threaded coroutine dispatcher, but I also want to provide a synchronous interface for my users. How can I do this?
j
you can run all the suspend functions through a Mutex() that only allows one suspend function at a time 🤔. But not sure if that would be the ideal solution for your usecase.
a
no it is not, i tried that but it is extremely slow
my current setup is fine
in regards to speed
i have presistent data structures so reads are not confined (no coroutines)
writes are confined, but I only want to return from a mutating method when the mutation is complete
j
so you have
Copy code
suspend fun doWrite(input): Result {}
and
Copy code
fun doWriteSync(input): Result {
    scope.launch{ doWrite(input) }
}
And the suspend function works fine and returns when it returns, but you want the synchronous blocking one to return only when the suspend one is done?
a
yes
g
scope.launch -> runBlocking?
2
a
i don't have access to
runBlocking
i'm not sure how can I use that
no code completion
a
try GlobalScope.runBlocking {}
g
is this MPP project?
runBlocking available only on JVM and Native, but not on JS (because there is just no proper way to block thread), so it’s not available there
☝️ 1
d
If you don't have a JS target, you can do expect/actual for
runBlocking
.
a
this is MPP, yes
so I have a workaround now
I refactored my methods which use coroutines to not return a value
and I have getters which aren't using coroutines but safe to call, because they are using persistent data structures
do any of you have a better idea for this?
p
If I understand correctly, you want to execute a sequence of write operations on some mutable shared state. Have you tried the
Channel
api. It behaves as a blockingQueue basically, where you can send message/operations in a queue manner.
a
no, as it turns out what I need is
@Synchronized
😄