Created
December 22, 2022 06:00
-
-
Save dandvl/ca41881df549ba8f47b0fab8a8d1be91 to your computer and use it in GitHub Desktop.
Async on Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.util.Log | |
import androidx.lifecycle.lifecycleScope | |
import kotlinx.coroutines.async | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.launch | |
import kotlin.system.measureTimeMillis | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
lifecycleScope.launch { | |
val timeSpent = measureTimeMillis { | |
val answer1 = async { longProcess() } | |
val answer2 = async { longProcess2() } | |
println(answer1.await()) | |
println(answer2.await()) | |
} | |
Log.d("test", "m: $timeSpent") | |
} | |
} | |
} | |
suspend fun longProcess(): String { | |
delay(2000L) | |
return "Answer 01" | |
} | |
suspend fun longProcess2(): String { | |
delay(4000L) | |
return "Answer 02" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment