Why Coroutines Are Preferred For Non-UI Related Works In Kotlin?
Coroutines are nothing but a process of computation which can be concurrent. It actually works like a thread but never block the execution of the codes. The codes of coroutines will run parallelly with the rest of codes of the application. So, the time required to execute a block of codes with coroutines will be much lesser than the time required to execute a block of codes with threads. We can say coroutines can perform the work of the threads but since it is light weight, it executes much faster. Let’s see how it will provide us advantages over threading in Android.
Comparative Discussion over Background Threads and Coroutines:
Here we have comparatively discussed on background threads and coroutines.
How background threads used to work on non-UI related functionalities:
In real world, android actually runs on single thread i.e., the UI-thread/Main thread. That means, whatever the function you’ll performed in background will reflect directly on the User Interface. But except that, lots of non-UI related work like: Database operation, Restful API calling, Network Calling or any long running background task, left to perform when you will build a professional application for the clients. This work will be performed by other threads like: Volley, Handler, Retrofit, services etc. If we need to update the UI part based on the work done by the other background threads, then we can return back the result to the UI with the help of Call-backs and various post methods.
Long running background task and function with Threads:
Any server related works like: sending request to server and get back a response from them and apart from that, loading/calling any file from your system (images, text files), related to long running task in the background as it could make a application to wait for a long amount of time to finish it’s process. In general, the next generation smartphones process any code too fast that is way out of our mind. Now we know that the user interfaces in android controlled by the main thread and it’s also in the charge for the user interaction. So, when a user performs multiple work in an application, there will be a chance that the application might take more time than the average response time. In terms of reducing the response time, we use call-back methods like post so that the network request could perform little bit faster but can’t provide a stable solution as the network request will be processed by other threads called through the main thread.
- Consumed time more when it comes to send any data between two threads.
- Threads are heavier as it will creates its own stack and thread scheduler implements extra headache to schedule the threads.
- If you add a simple delay in your operation the thread would block the whole execution and the next operation will not get a chance to get executed within that moment.
- Threads are not aware about the lifecycle of the android. So, when a UI get finished/destroyed, thread would run as it’s own.
So, using lots of thread in an application will make it too much difficult to understand the important mechanism and the logic of the application and we may end up by only focusing on the call-back mechanism of the threads rather than its own functionality.
Hustle free and lightweight mechanism of coroutines in Kotlin:
One can think of a coroutine as a light-weight thread. Like threads, coroutines can run in parallel, wait for each other and communicate. The biggest difference is that coroutines are very cheap, almost free: we can create thousands of them, and pay very little in terms of performance. True threads, on the other hand, are expensive to start and keep around. A thousand threads can be a serious challenge for a modern machine. So we can say coroutines are nothing but lightweight threads. Coroutines provide us an easy way to do synchronous and asynchronous programming. Coroutines allow execution to be suspended and resumed later at some point in the future which is best suited for performing non-blocking operations in the case of multithreading.
Advantages we will get if we use coroutines
- They are light-weight
- Built-in cancellation support
- Lower chances for memory leaks
- Jetpack libraries provide coroutines support
Safety features of Coroutines:
In Kotlin coroutines, well written suspend functions are always safe to call from the main thread. No matter what they do, they should always allow any thread to call them. But, there’s a lot of things we do in our Android apps that are too slow to happen on the main thread. Network requests, parsing JSON, reading or writing from the database, or even just iterating over large lists. Any of these have the potential to run slowly enough to cause user visible “jank” and should run off the main thread. Using suspend doesn’t tell Kotlin to run a function on a background thread. It’s worth saying clearly and often that coroutines will run on the main thread. In fact, it’s a really good idea to use Dispatchers.Main.immediate when launching a coroutine in response to a UI event — that way, if you don’t end up doing a long running task that requires main-safety, the result can be available in the very next frame for the user in UI.
I hope you learnt something new from this blog. Please share it with your friends and stay tuned for more updates. If you are an IT enthusiastic, and want to gather more knowledge, you can go through some of our blogs given below.
- Android courses
- App Development
- Artificial Intelligence Course
- Cloud Computing Course
- Content Writing
- Crash Course
- Digital Marketing
- Embedded System and Robotics Course
- Ethical Hacking and Cyber Security Course
- How To
- Internet of Things (IoT) Course
- iOS App Development
- iPhone courses
- IT Certification Course
- Machine Learning with Python Course
- Mean stack
- Mern stack
- NET Development
- Networking with Cisco Tools Course
- PHP Variable
- Professional IT course
- Python Course
- React Native
- SAP Development
- Social Media
- Software Testing
- Successful Career
- Tech Industry
- Tech News & Tips
- UI/UX Design Course
- Web Design