# coroutines

Jason Hartley

02/28/2023, 5:52 PM
I need advice. I'm updating an app that uses Threads and Runnables for a handful of background tasks that generally stay running for the lifetime of the app, but can be terminated based on various events. For example, one of these Runnables is actively receiving data from a USB accessory and passing it on to listeners, but can be killed if the USB connection is lost. The way it's currently architected is a foreground service stays running that executes these Threads/Runnables on a ThreadPoolExecutor. I'd like to convert this all to coroutines, but I have to admit that I have virtually no experience working with coroutines directly. What might be a good general approach for converting these Threads/Runnables to coroutines?

Casey Brooks

02/28/2023, 6:19 PM
Your use-case does sounds like a good fit for migrating to coroutines (though i have no idea how performance will compare to your current setup), but it definitely doesn’t sounds like a trivial use-case. I’d recommend learning the basics of coroutines first, before starting to apply them to this situation, so you can make sure you understand enough to set up the proper structure for your app. The Coroutines guide is a good place to start, and will teach you all the basics and introduce many of the available APIs that you can use to implement your solution.
At a very high level, with coroutines you generally won’t be thinking in terms of individual threads (so don’t use thread-locals), but in terms of units of work that are running asynchronously (could be in series or parallel). Instead of a ThreadPoolExecutor, you’ll have a
which includes a Dispatcher (such as
). One of your Runnables would be a coroutine started with
coroutineScope.launch { }
. Rather than passing data to listeners, you might use a
to pass data around. If the USB connection is lost, then you would cancel the CoroutineScope to stop processing the data and shut down the tasks that were launched into it. This of course glosses over many of the details, but hopefully it gives you a place to start and some specific terms/APIs to look into

Jason Hartley

02/28/2023, 6:40 PM
Thank you, Casey. This is very helpful!