Wednesday, July 22, 2020

android kotlin - Coroutines async with timeout

MainActivity.kt

package com.example.coroutine

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.io.IOException
import java.net.MalformedURLException
import java.net.URL


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // url of image to download
        val urlImage:URL? = try {
            URL("https://images.pexels.com/photos/1031770/" +
                    "pexels-photo-1031770.jpeg?" +
                    "auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260")
            }catch (e:MalformedURLException){
                button.isEnabled = false
                button2.isEnabled = false
                textView.text = e.message
                null
            }


        button.setOnClickListener {
            textView.text = "Image downloading. Timeout 500 milliseconds.\n"

            urlImage?.apply {
                asyncImageDownload(this, 500)
            }
        }


        button2.setOnClickListener {
            textView.text = "Image downloading. Timeout 10000 milliseconds.\n"
            urlImage?.apply {
                asyncImageDownload(this, 10000)
            }
        }
    }


    // asynchronously download image from url with predefined timeout value
    private fun asyncImageDownload(url:URL,timeout:Long){
        progressBar.visibility = View.VISIBLE

        val result : Deferred<Bitmap?> = lifecycleScope.async(Dispatchers.IO) {
            url.toBitmap()
        }

        val job = lifecycleScope.launch (Dispatchers.Main){
            val bitmap : Bitmap? = withTimeout(timeout){
                result.await()
            }

            bitmap?.apply {
                imageView.setImageBitmap(bitmap)
                textView.append("\nDownload finish.")
                progressBar.visibility = View.INVISIBLE
            }

            if (bitmap == null){
                imageView.setImageBitmap(null)
                textView.append("\nDownload failed.")
                progressBar.visibility = View.INVISIBLE
            }
        }

        job.invokeOnCompletion {
            it?.apply {
                textView.append("\n\nDownload failed.")
                textView.append("\n\nERROR : $message")
                imageView.setImageBitmap(null)
                progressBar.visibility = View.INVISIBLE
            }
        }
    }
}


// extension function to get / download bitmap from url
fun URL.toBitmap(): Bitmap?{
    return try {
        BitmapFactory.decodeStream(openStream())
    }catch (e: IOException){
        null
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FCE883"
    tools:context=".MainActivity">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:backgroundTint="#701C1C"
        android:text="Download 500 ms"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:backgroundTint="#701C1C"
        android:text="10000 ms"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="parent" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="@+id/button2"
        app:layout_constraintStart_toEndOf="@+id/button2"
        app:layout_constraintTop_toTopOf="@+id/button2" />

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/textView"
        style="@style/TextAppearance.MaterialComponents.Headline6"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:padding="8dp"
        android:fontFamily="sans-serif-thin"
        android:textColor="#353839"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:text="TextView" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="250dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        tools:srcCompat="@tools:sample/avatars" />

</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle (app) [code to add]

dependencies {
    // kotlin coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'

    // life cycle
    def lifecycle_version = "2.2.0"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}