when i have this code: ``` launch { ... } ``` is t...
# coroutines
h
when i have this code:
Copy code
launch {
...
}
is this async? because i want to have some stuff done async, and then after the async, i want to go back to the main thread and call a sync function
s
Launches new coroutine without blocking current thread and returns a reference to the coroutine as a Job
h
so its concurrent but not async?
s
It is always async, as opposed to blocking, but if its concurrent depends on other factors.
It is a bit easier to talk about if you have an example of what you want
h
SO THEN HOW CAN I RETURN TO THE MAin thread?
oops, my bad with caps
s
I am not sure what you mean by return to the main thread. You can either block the main thread waiting for the async operation to complete or if the main thread has an eventloop of some kind, then schedule something on it when the async operation is complete. I think
Job.invokeOnCompletion
is the right method for that
h
i am worrking with an api that can only be invked on the main thread.
i want to schedule every 20 mins tho.
so i want it to wait asynchronously, then swytch to the main thread for completion
u
Which platform? Plain Java, Android?
h
plain ol’ java
u
And what kind of workload? io bound or cpu bound
h
cpu
a lot of processing
u
To jump back to the main thread, you need some dispatcher that dispatchers your work to e.g. an event loop running on the main thread
h
can you link me somewhere where ic an read more about this, or give me an example?
u
UI frameworks like Javafx, swing,... come with such an event loop. If your framework does not have that your only chance is to wrap the whole program into runBlocking.
h
i see. i’ll look into it if it has any such. thank you!
u
With a ui dispatcher you can go: launch { doStuff(); withContext(Dispatcher.UI) { callAPI() } }