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

addamsson

08/08/2019, 9:11 AM
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

Jacques Smuts

08/08/2019, 9:13 AM
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

addamsson

08/08/2019, 9:14 AM
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

Jacques Smuts

08/08/2019, 9:19 AM
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

addamsson

08/08/2019, 9:33 AM
yes
g

gildor

08/08/2019, 9:33 AM
scope.launch -> runBlocking?
2
a

addamsson

08/08/2019, 9:34 AM
i don't have access to
runBlocking
i'm not sure how can I use that
no code completion
a

ahulyk

08/08/2019, 9:44 AM
try GlobalScope.runBlocking {}
g

gildor

08/08/2019, 9:46 AM
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

Dominaezzz

08/08/2019, 10:47 AM
If you don't have a JS target, you can do expect/actual for
runBlocking
.
a

addamsson

08/08/2019, 11:03 AM
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

Pablichjenkov

08/08/2019, 2:42 PM
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

addamsson

08/18/2019, 2:45 PM
no, as it turns out what I need is
@Synchronized
😄
7 Views