Thursday, July 23, 2020

android kotlin - Coroutines with timeout or null

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/298246/" +
                    "pexels-photo-298246.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 {
            urlImage?.apply {
                asyncImageDownload(this, 600)
            }
        }


        button2.setOnClickListener {
            urlImage?.apply {
                asyncImageDownload(this, 12000)
            }
        }
    }


    // asynchronously download image from url with predefined timeout value
    private fun asyncImageDownload(url:URL,timeout:Long){
        textView.text = "Image downloading. Timeout $timeout milliseconds.\n"
        progressBar.visibility = View.VISIBLE

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

        lifecycleScope.launch(Dispatchers.Main){
            // coroutine with a specified timeout and
            // returns null if this timeout was exceeded
            val bitmap : Bitmap? = withTimeoutOrNull(timeout){
                    result.await()
                }

            if (bitmap == null){
                textView.append("\nTimed out. Download failed.")
                imageView.setImageBitmap(null)
                progressBar.visibility = View.INVISIBLE
            }else{
                textView.append("\nDownload finish.")
                imageView.setImageBitmap(bitmap)
                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="#ECEBBD"
    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="#FF2400"
        android:text="Download 600 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="#FF2400"
        android:text="12000 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="#59260B"
        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="300dp"
        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"
}