package com.example.coroutine
import kotlinx.coroutines.*
class UserDataManager1 {
//structure
var count = 0
lateinit var deferred : Deferred<Int>
suspend fun getTotalUserCount():Int {
coroutineScope {
launch(Dispatchers.IO) {
delay(1000)
count = 50
}
deferred = async(Dispatchers.IO) {
delay(3000) //create a delay
return@async 70
}
}
return count + deferred.await() // 120
}
}
package com.example.coroutine
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainActivity : AppCompatActivity() {
private var count = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnCount.setOnClickListener {
tvCount.text = count++.toString()
}
btnDownloadUserData.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
tvUserMessage.text = UserDataManager1().getTotalUserCount().toString()
}
}
}
}<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center_vertical"
tools:context=".MainActivity">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvUserMessage"
android:textSize="20sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
/>
<Button android:text="@string/download_user_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnDownloadUserData"
android:layout_marginBottom="68dp"
android:textSize="24sp"
android:background="@color/colorPrimaryDark"
android:textColor="@android:color/white"
android:padding="15dp"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvCount"
android:textSize="20sp"
tools:text="Count"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
/>
<Button android:text="@string/click_here"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnCount"
android:background="@color/colorPrimaryDark"
android:textSize="24sp"
android:textColor="@android:color/white"
android:padding="15dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
/>
</LinearLayout>
No comments:
Post a Comment