avatarAntroid

Summary

The provided text discusses synchronous and asynchronous programming in the context of mobile application development, particularly focusing on Android.

Abstract

The text begins by describing a synchronous operation, such as downloading and displaying an image in a mobile application. It then explains how synchronous operations can block the UI, leading to a less responsive user interface. The text then introduces asynchronous programming, using the same image loading example, and explains how asynchronous programming avoids blocking the main thread while downloading, decoding, and updating the UI, allowing the application to remain responsive. The text also discusses the importance of asynchronous programming in mobile development and provides examples of synchronous and asynchronous network calls.

Opinions

  • Synchronous operations can lead to blocking the execution of the program, potentially causing the application to become unresponsive.
  • Asynchronous programming is particularly valuable in mobile development, where responsiveness and smooth user interactions are crucial.
  • Synchronous network calls on the main thread in mobile applications are not recommended, as they can result in a poor user experience due to potential UI freezes and app crashes.
  • Asynchronous network calls allow the application to remain responsive during potentially time-consuming operations, such as fetching data from a server.

What is? — Synchronous and Asynchronous — Android

Heard many times but often wondered what’s what??

Let’s find out.

from here

Synchronous Computing:

Consider a simple synchronous operation in a mobile application, such as downloading an image from the internet and displaying it on the screen. In a synchronous approach, the code might look like this:

fun loadImage(url: String): Bitmap {
    // Synchronous network request to download image
    val imageData = networkClient.downloadImage(url)

    // Synchronous decoding of image data
    val bitmap = ImageDecoder.decodeBitmap(imageData)

    // Synchronous UI update
    imageView.setImageBitmap(bitmap)

    // Execution waits for each step to complete before moving to the next
    return bitmap
}

/**
*
* `loadImage` function performs each step (download, decode, and update UI)
* synchronously. If any of these steps take a significant amount of time,
* the entire operation will block, potentially 
* leading to a less responsive user interface.
*
**/

One Liner :

Synchronously — If operation takes more time it will hold up the ui flow.

  • Tasks will be executed sequentially, one after the other, and the program waits for each task to complete before moving on to the next one. This means that the execution of the program is synchronized, and each operation blocks the execution until it finishes.

Asynchronous Computing :

Using asynchronous programming, the same image loading example might look like this:

fun loadImageAsync(url: String) {
    // Asynchronous network request to download image
    networkClient.downloadImageAsync(url) { imageData ->
        // Asynchronous decoding of image data
        ImageDecoder.decodeBitmapAsync(imageData) { bitmap ->
            // Asynchronous UI update
            imageView.setImageBitmap(bitmap)
        }
    }
}

/**
*
* `loadImageAsync` function uses asynchronous callbacks 
*  or other mechanisms(coroutines) to avoid blocking the main thread
*  while downloading, decoding, and updating the UI.
*  This allows the application to remain responsive, and the user can
*  continue interacting with the app while the image is being loaded.
*
**/

One Liner :

ASynchronously — The operation can take its time and perform computing in background while the UI flow is not affected and runs smoothly.

Asynchronous programming is particularly valuable in mobile development, where responsiveness and smooth user interactions are crucial. It allows developers to perform time-consuming tasks in the background without freezing the user interface, improving the overall user experience.

Now, Does making a network call, Synchronous or Asynchronous operation? One might be curious to ask.

Well it depends. on how it is implemented.

  1. Synchronous Network Call:

In a synchronous network call, the application waits for the network operation to complete before proceeding to the next line of code. This approach can lead to blocking the execution of the program until the network call finishes, potentially causing the application to become unresponsive during the operation.

// Synchronous network call
val connection = URL("https://example.com").openConnection() as HttpURLConnection
val inputStream = connection.getInputStream()
// Continue processing after the network call completes

It’s generally not recommended to perform synchronous network calls on the main thread in mobile applications, as it can result in a poor user experience due to potential UI freezes, and can lead to app crash.

2. Asynchronous Network Call:

In an asynchronous network call, the application initiates the network operation and continues with other tasks without waiting for the network call to finish. Callbacks, listeners, or other mechanisms are used to handle the result of the network operation when it becomes available.

// Asynchronous network call using Retrofit
val service = Retrofit.Builder().baseUrl("https://example.com").build().create(MyApiService::class.java)
service.getData().enqueue(object : Callback<DataResponse> {
    override fun onResponse(call: Call<DataResponse>, response: Response<DataResponse>) {
        // Handle response asynchronously
        val data = response.body()
        // Continue processing
    }

 override fun onFailure(call: Call<DataResponse>, t: Throwable) {
        // Handle failure asynchronously
    }
})

// Continue processing without waiting for the network call to complete

Asynchronous network calls are mostly used in mobile development, as they allow the application to remain responsive during potentially time-consuming operations, such as fetching data from a server.

Hope it helped you connect next time if some one mentions of Synchronous or Asynchrounous .

To see how you can use Kotlin Coroutines in Android to make calls Asynchronously you can check out this article here.

Synchronous Programming
Asynchronous Programming
Mobile App Development
Android
Android App Development
Recommended from ReadMedium