https://kotlinlang.org logo
Title
h

Hamza

10/03/2018, 3:28 AM
when i have this 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

spand

10/03/2018, 6:50 AM
Launches new coroutine without blocking current thread and returns a reference to the coroutine as a Job
h

Hamza

10/03/2018, 8:21 AM
so its concurrent but not async?
s

spand

10/03/2018, 8:33 AM
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

Hamza

10/03/2018, 8:35 AM
SO THEN HOW CAN I RETURN TO THE MAin thread?
oops, my bad with caps
s

spand

10/03/2018, 8:45 AM
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

Hamza

10/03/2018, 8:47 AM
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

uli

10/03/2018, 9:24 AM
Which platform? Plain Java, Android?
h

Hamza

10/03/2018, 9:24 AM
plain ol’ java
u

uli

10/03/2018, 9:35 AM
And what kind of workload? io bound or cpu bound
h

Hamza

10/03/2018, 10:08 AM
cpu
a lot of processing
u

uli

10/03/2018, 10:18 AM
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

Hamza

10/03/2018, 10:19 AM
can you link me somewhere where ic an read more about this, or give me an example?
u

uli

10/03/2018, 10:21 AM
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

Hamza

10/03/2018, 10:22 AM
i see. i’ll look into it if it has any such. thank you!
u

uli

10/03/2018, 10:37 AM
With a ui dispatcher you can go: launch { doStuff(); withContext(Dispatcher.UI) { callAPI() } }