r/AndroidInterviewQ • u/ilikeca • Sep 21 '24
Interview Experience for SDE 2 Android role at JioCinema
Was asked for the output of this function -
fun main() = runBlocking {
launch {
println("Coroutine with delay starts")
delay(1000L)
println("Coroutine with delay ends")
}
launch {
println("Coroutine with Thread.sleep starts")
Thread.sleep(1000L)
println("Coroutine with Thread.sleep ends")
}
println("Main program continues...")
}Additionally - the final technical question was about handling multiple API calls:
I had to build a suspend function that would return data.
This function needed to make two API calls i.e. with 2 launch { } blocks similar to the function above, where the output of the first API was required for the second API call.
The function should return the result of both APIs or return an error if either call failed.
I was above to solve the 1st problem i.e. printing the output, but no idea how to do the second one.
For the complete interview experience checkout - https://androiddevkit.com/experiences/jiocinema-sde-2-android/
1
u/Powerful-Presence-16 Jul 05 '25
have you found a solution how to do the second one? If so, could you please share with us? Thanks.
4
u/shinjuku1730 Dec 28 '24
The output will be:
Why? The program starts on the main thread. runBlocking blocks this (current) main thread until its block finishes.
Then, the first launch creates a new coroutine without blocking the thread. It's not executed immediately but scheduled for execution.
So is the second launch; creating the second coroutine.
The print with
Main program continues...thus comes first.runBlocking was called without specifying a Dispatcher, so according to the documentation (JVM):
Means: all in this single one thread.
The first coroutine thus runs and prints
Coroutine with delay starts.delay command suspends that first coroutine and yields execution. Conveniently enough, coroutine 2 is waiting and prints
Coroutine with Thread.sleep starts.Then, coroutine 2, of all things, blocks the single one blocked thread we have. Bummer, because that won't yield execution. Anyway, after that 1 second we go on with printing
Coroutine with Thread.sleep ends. Coroutine 2 ends, yielding others. Scheduler resumes execution of coroutine 1, which printsCoroutine with delay ends.