1 year ago

#379730

test-img

Mikey Chen

When to use withContext(NonCancellable) versus WorkManager to run code after app is killed/backgrounded?

I have a simple and fast operation such as inserting an important log into an on-disk database. This needs to be guaranteed even if the user closes the app (we don't want to lose the log), and so my initial hunch was to use WorkManager to guarantee that this task runs and inserts it into the database.

However, upon learning about the NonCancellable coroutine context, I'm wondering if withContext(NonCancellable) is better. Since adding a single event to a database is a very fast operation, I'm wondering if using WorkManageris overkill here - the API documentation says WorkManager should be used for long-running, persistent work (like making network requests, etc)

What are the situations in which withContext(NonCancellable) is appropriate to be used over WorkManager, outside of code that handles cleanup?

android

kotlin-coroutines

android-workmanager

0 Answers

Your Answer

Accepted video resources