02.Android Background Task
Tags: kotlin, android, threading
Published: 2023-02-13 23:39:26



> ## Threading/ Multi-Thered

"Threads" are the individual units of execution within a process. Each thread represents a separate flow of control, and has its own program counter, stack, and set of CPU registers.When a program is multi-threaded, each thread runs concurrently and independently of the other threads, allowing the program to perform multiple tasks at the same time.

"Threading" refers to the ability of an operating system to manage the execution of multiple tasks simultaneously within a single process.

Suppose you have a program that performs two tasks: task A and task B. Task A involves downloading a large file from the internet, while task B involves processing the data from the downloaded file.

If the program is single-threaded, it would execute task A, wait until the download is complete, then execute task B. This means that while the program is waiting for the download to complete, it can't do anything else.

If the program is multi-threaded, it could execute both tasks A and B concurrently, with each task running on a separate thread. While task A is downloading the file, task B can start processing the data from previous downloads. This would allow the program to perform both tasks more efficiently and in a shorter amount of time.

**Handlers,Looper & MessageQueue:** Handlers, Looper, and MessageQueue are core components of the Android platform that are used to perform background tasks in an Android application.

A Handler is an object that allows to send messages to a background thread.

The Handler is associated with a Looper, Each thread in an Android application has a unique Looper and MessageQueue.The MessageQueue is used by the Looper to manage the messages that are sent to a background thread. The Looper retrieves messages from the MessageQueue, dispatches the messages to the appropriate Handlers, and processes the messages in the order they were added to the queue.

You can use a Handler to send messages to a background thread, and the Looper and MessageQueue are responsible for managing the message loop and processing the messages in the background thread.

> ## Synchronized

In a synchronized process, each thread waits for the others to complete their tasks before proceeding with its own. This ensures that the shared resources are used in a consistent and predictable manner, and prevents race conditions and other synchronization issues.

An example of a synchronized process is a bank transaction. If multiple customers try to withdraw money from the same account simultaneously, a race condition could occur. To prevent this, the bank uses a synchronized process that ensures that only one customer can access the account at a time. The other customers must wait until the current transaction is complete before they can access the account.

> ## Asynchronous

Asynchronous programming is a way of writing code that allows multiple tasks to run concurrently, without blocking the execution of other tasks. 

This is especially important in applications that require I/O-bound or long-running operations, as it can improve the overall performance and responsiveness of the application.

An example of an asynchronous process is a web browser. When a user requests a web page, the browser can download multiple elements of the page (such as images, videos, and scripts) simultaneously, without waiting for each element to be downloaded before starting the download of the next. This allows the page to load more quickly and efficiently.

- Network operations,
- Database queries
- Background, and update the UI  or 
- Any other long-running task

Library for asynchronous programming:

**AsyncTask:**The AsyncTask is a pre-built Android class that allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. AsyncTask provides an easy way to run code in the background and update the UI from the results of that code. You can use it to run network operations, database queries, or any other long-running task that should not block the main thread.The AsyncTask class takes care of creating a separate thread for the background operation, so you can focus on the task at hand.

**RxKotlin/RXJava:**RxKotlin is a library ReactiveX (Rx). With RxKotlin, you can write concise and expressive code to handle complex asynchronous and event-driven scenarios, such as managing network requests, handling user interactions, or working with reactive data sources.RxKotlin is built on top of the RxJava library

**Kotlin coroutines:** Kotlin coroutines is a feature in the Kotlin programming language that provides a way to write asynchronous, non-blocking, and concurrent code in a more concise, easier to understand and maintainable  and readable way. You can use coroutines to write code that performs long-running operations, such as network requests or database queries, in the background, and update the UI with the results when the operation is complete.

Kotlin coroutines provide a simple and straightforward way to write asynchronous code, while RxKotlin provides a more comprehensive and flexible approach to working with asynchronous and event-driven data streams.If you're new to asynchronous programming in Android, I would recommend starting with Kotlin coroutines, as they are a simple and straightforward solution for many common use cases. If you're working on a complex project that requires a more comprehensive and flexible approach to asynchronous programming, RxKotlin may be the better choice.

**Kotlin flows:** Kotlin Flows provide a simple and intuitive way to handle asynchronous data streams, and are well-suited for many common use cases, such as performing network requests, database queries, or other long-running operations in the background. Flows are lightweight and easy to understand, and can be easily managed and scheduled by the Kotlin runtime.

**RxAndroid/AndroidX:** RxAndroid/AndroidX, on the other hand, provides a more comprehensive and flexible approach to working with asynchronous and event-driven data streams. RxAndroid/AndroidX is built on top of the RxJava library and provides a reactive programming model that can handle complex asynchronous scenarios, such as managing network requests, handling user interactions, or working with reactive data sources.

If you're looking for a simple and intuitive solution for handling asynchronous data streams, Kotlin Flows may be the better choice. If you're working on a complex project that requires a more comprehensive and flexible approach to asynchronous programming, RxAndroid/AndroidX may be the better choice. 

> ## Singletons

---

> ## Parcelable & Serialization

Both Parcelable and Serialization are used for object serialization in Android, but they have different strengths and weaknesses. If you're looking for a more performance-oriented solution for object serialization, Parcelable may be the better choice. If you're looking for a more flexible and compatible solution, Serialization may be the better choice.

**Parcelable** is an Android-specific interface that provides a more efficient way of serializing and deserializing objects. It can be faster than the traditional Java Serialization mechanism. The main advantage of Parcelable is its performance, as it requires less memory overhead and can be faster in terms of serialization and deserialization speed.

On the other hand, **Serialization**, is a general-purpose mechanism for serializing and deserializing objects in Java. It provides a more flexible and powerful mechanism for serializing and deserializing objects, but it can be slower and use more memory than Parcelable. It can be used with any Java-based platform and can handle more complex object structures.

> ## keywords

async, await, suspend are keywords are keyword that allow you to write asynchronous code.

**Async:** is used to declare a method as asynchronous 

**Await:** is used to specify that a certain operation should be performed asynchronously. The "await" keyword is used to specify the point at which the asynchronous method should pause its execution until the awaited task is completed. 

**"Suspend"** is used in coroutines to indicate that the function can be paused and resumed at any time without blocking the calling thread.By using "suspend", the developer can write asynchronous code that is easy to read, understand, and maintain.