Because coroutines support suspend and resume, the coroutine on the main thread will be resumed with the result as soon as the withContext block is complete. In this example, fetchDocs is executing on the main thread, but can safely call get which performs a network request in the background. So a good practice is to use withContext to make sure every function is safe to be called on any Dispatcher including Main - that way the caller never has to think about what thread will be needed to execute the function. Because withContext lets you control what thread any line of code executes on without introducing a callback to return the result, you can apply it to very small functions like reading from your database or performing a network request. With coroutines you can do thread dispatch with fine-grained control. With callbacks, fetching might look like this: class ViewModel: ViewModel() // Dispatchers.Main Callbacks provide a handle to a library that it can use to call back into your code at some future time. In order to perform a network request off the main thread, a common pattern is callbacks. Any long running task should be done without blocking the main thread, so your app doesn’t display what’s called “jank,” like frozen animations, or respond slowly to touch events. If there is too much work happening on this thread, the app appears to hang or slow down, leading to an undesirable user experience. On Android, every app has a main thread that is in charge of handling UI (like drawing views) and coordinating user interactions. In one blink of an eye, or a somewhat slow network request, the CPU can execute over one billion cycles! However, if you think of a network request as one blink of the eye, around 400 milliseconds (0.4 seconds), it’s easier to understand how fast the CPU operates. On a Pixel 2, a single CPU cycle takes just under 0.0000000004 seconds, a number that’s pretty hard to grasp in human terms. It can be hard to understand how fast a modern phone executes code compared to a network request. These sorts of things are what I call long running tasks - tasks that take far too long for your app to stop and wait for them! Similarly, reading from a database or loading an image from disk involve reading a file. Let’s dive in to each to see how coroutines can help us structure code in a cleaner way! Long running tasksįetching a webpage or interacting with an API both involve making a network request. Main-safety allows you to ensure that any suspend function can be called from the main thread.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |