MainActivity.kt
package com.example.coroutine
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// url to get html
val url:URL = URL("https://developer.android.com/")
button.setOnClickListener {
// creates a coroutine and returns its future result
// as an implementation of deferred
// async task to get html as string from url
val result: Deferred = GlobalScope.async {
url.getHtml()
}
// global scope is used to launch top-level coroutines which are
// operating on the whole application lifetime
GlobalScope.launch(Dispatchers.Main) {
// show html as string when available
textView.text = result.await()
}
}
}
}
// extension function to get html from url
fun URL.getHtml():String {
val reader = BufferedReader(InputStreamReader(this.openStream()))
var input: String? = ""
val stringBuffer = StringBuffer()
while (reader.readLine().also { input = it } != null) {
stringBuffer.append(input)
}
reader.close()
return stringBuffer.toString ()
}
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"
tools:context=".MainActivity"
android:background="#EDEAE0">
<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:text="Get HTML" android:backgroundTint="#665D1E"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
<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:padding="8dp" android:layout_marginTop="16dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
tools:text="Hello World!" />
</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle (app) [dependencies]
// kotlin coroutineimplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'