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

mzgreen

12/06/2023, 11:24 AM
Hey! I’d like to execute a suspend function on a bg thread and after some time if it still hasn’t finished its work then I’d like to block the main thread and wait until it finishes. Imagine an app with a screen and a button that takes you to the next screen. At some point I’d like to run some code on bg thread, and then if the user taps on a button two things can happen: 1) my function already finished so I just navigate to the next screen, or 2) my function is still running so I’d like to block the main thread and wait until it finishes and then continue with navigation. I’ve tried to do sth like:
Copy code
val job = launch { someBackgroundWork() }

//... at some point later user clicks on the button
button.onClick {
  runBlocking {
    job.join()
  }
  // navigate to the next screen
}
so this blocks the main thread as expected but for some reason it never unblocks it. I’ve added the logs and I can see that someBackgroundWork finishes the work but the main thread is still blocked. What am I missing? Maybe I shouldn’t use runBlocking at all and there is a nicer way to do this?
a

Alex Prince

12/06/2023, 8:42 PM
it's most likely the runBlocking, I've run into main thread deadlocks that way before. I'd be tempted to come at it the other direction if it were me, disable the button, then once the bg worker finishes, re-enable the button, rather than waiting on click. If you do actually block main, you'll probably run into UX issues (I'm coming from the android perspective here, where that'll throw ANRs pretty quick)
m

mzgreen

12/06/2023, 8:46 PM
Thanks. Yea I know it won't be the best ux but it's not up to me to change this requirement. It's also a pretty fun coroutines puzzle :D there are tons of blog posts showing how cool coroutines are because they don't block the main thread but when I actually need to do it I have no idea how! It's probably good thing and a proof how nicely designed coroutines api is but I'd like to do it and learn something new anyways :)
a

Alex Prince

12/06/2023, 8:47 PM
yea definitely! you could just launch from there rather than the runblocking probably, as long as the click handler was in the launch as well