Friday, July 17, 2020

android kotlin - Coroutines async await all

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 kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.io.IOException
import java.net.URL


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

        // urls of images
        val urlImage1 = URL("https://images.pexels.com/photos/1080762/" +
                "pexels-photo-1080762.jpeg?" +
                "auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260")

        val urlImage2 = URL("https://images.pexels.com/photos/1118440/" +
                "pexels-photo-1118440.jpeg?" +
                "auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260")

        val urlImage3 = URL("https://images.pexels.com/photos/980384/" +
                "pexels-photo-980384.jpeg?" +
                "auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260")


        button.setOnClickListener {
            it.isEnabled = false
            progressBar.visibility = View.VISIBLE

            // run coroutines with global scope
            with(GlobalScope){
                // asynchronously get / download bitmaps from urls
                val deferreds : List<Deferred<Bitmap?>> = listOf(
                    async { urlImage1.toBitmap() },
                    async { urlImage2.toBitmap() },
                    async { urlImage3.toBitmap() }
                )

                // coroutine dispatcher that is confined to the
                // main thread operating with ui objects
                launch(Dispatchers.Main){
                    // awaits for completion of given deferred
                    // values without blocking a thread
                    deferreds.awaitAll().apply {
                        imageView.setImageBitmap(get(0))
                        imageView2.setImageBitmap(get(1))
                        imageView3.setImageBitmap(get(2))

                        progressBar.visibility = View.INVISIBLE
                        it.isEnabled = true
                    }
                }
            }
        }
    }
}


// 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="#FFFAF0"
    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="#9FA91F"
        android:text="Get Images From URLs"
        app:layout_constraintStart_toStartOf="parent"
        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/button"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="@+id/button" />

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

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="160dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        tools:srcCompat="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="0dp"
        android:layout_height="160dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        tools:srcCompat="@tools:sample/avatars" />

</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle (app) [dependencies]

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