-
Notifications
You must be signed in to change notification settings - Fork 24
How asynchronous programming works
Devrath edited this page Oct 5, 2021
·
8 revisions
- User Interface is something an end-user uses to interact with the system.
- Using this mechanism the end-user interacts with the mobile and communicates with it to perform certain tasks.
- Once the tasks get completed, we show the result to the end-user.
- If the task that is being performed is taken a lot of time, we need to show feedback to the end-user that a task is in progress, otherwise the user thinks that the application is not responding, or worse it doesn't work at all.
- Once good example is that, say we are uploading a photo to the server and this photo is very large so naturally it takes time to upload the photo.
- Since it is taking a lot of time we need to show some feedback to users that an uploading task is in progress.
- We can do this by showing a loader to the end-user and once the uploading is done, we close the loader.
fun uploadImageToServer(image: Image) {
showLoader() // --- > This triggers spinning of loader and starts displaying loader
service.upload(image) // --- > Here the data is sent as bytes to server
hideLoader() // --- > This triggers spinning of loader and stops displaying loader
}
- Here in this simple function
uploadImageToServer
lot of things happen -
showLoader()
calls the loader to display, Now let's assume we are calling the android loader, this is not just a call it's an android functionality built that shows an animation. But so it's doing some operation. - If
service.upload
need to wait untilshowLoader()
gets completed theservice.upload
becomes a blocking call. - Similarly
hideLoader()
functionality to stop the above loader - So here the concept of multi-threading comes to the picture, If we have many threads that perform tasks parallel, We can do more things at once.
- In the above example, We show the loader in
UI-thread
and theservice call
, we perform in a background thread doing so we need not need to wait for individually things to complete to continue to next instead, We can do things parallel.
- We use the main thread to manage the UI
- Each application has only one thread called
main thread
to avoid the deadlock. - We use the many threads to achieve what we called concurrency with the help of multi-threading.
- Understanding how threads communicate is the key to knowing concurrency.
- All threads should be able to communicate between them seamlessly without causing problems.