Friday, July 17, 2020

android kotlin - Coroutines cancel job

MainActivity.kt

package com.example.coroutine

import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*


class MainActivity : AppCompatActivity() {

    lateinit var job:Job

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

        button.setOnClickListener {
            // initialize the job
            job = GlobalScope.launch(Dispatchers.Main) {
                textView.setTextColor(Color.parseColor("#006A4E"))
                textView.text = "Loop through 10 down to 0"

                for(i in 10 downTo 0){
                    delay(1000)
                    textView.append("\n" + i)
                }
            }

            // invoke on job completion
            job.invokeOnCompletion {
                it?.apply {
                    textView.setTextColor(Color.parseColor("#800020"))
                    textView.append("\n\n" + message)
                }
            }
        }


        btnCancel.setOnClickListener {
            if (this::job.isInitialized){
                if (job.isActive){
                    // cancel the job
                    job.cancel(
                        "Job cancelled by user." // message
                    )
                }else{
                    textView.text = "Job is not active."
                }
            }else{
                textView.text = "Job is not initialized."
            }
        }
    }
}
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="#EDEAE0"
    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="#006B3C"
        android:text="Launch Job"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnCancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:backgroundTint="#CB4154"
        android:text="Cancel"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintStart_toEndOf="@+id/button" />

    <TextView
        android:id="@+id/textView"
        style="@style/TextAppearance.MaterialComponents.Headline5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:padding="8dp"
        android:textStyle="italic|bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:text="TextView" />

</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'