Member-only story
Understanding Asynchronous, Concurrency, and Parallelism in Android Development (Kotlin) 🚀
When working with Kotlin in Android development, handling tasks efficiently is crucial, especially for UI responsiveness. Concepts like asynchronous programming, concurrency, and parallelism play a significant role in optimising performance.
1. Asynchronous Programming in Kotlin
- Asynchronous programming allows tasks to run without blocking the main thread.
- Instead of waiting for a task to complete, it lets other tasks execute while waiting.
- This is essential in Android to keep the UI responsive.
Example of Blocking vs. Asynchronous Code
Blocking Code (Synchronous)
@Composable
fun BlockUIThroughThread(
modifier: Modifier = Modifier
) {
LazyColumn(
modifier = modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(16.dp)
) {
item {
Button(onClick = {
Thread.sleep(5000) // UI blocked for 5 secs
}) {
Text(text = "Click")
}
}
items(100) {
Text(text = "Text $it")
}
}
}
đź’ˇ When click on button UI freezes for 5 seconds making the app unresponsive, because it called in the Main Thread.
Asynchronous Code using Coroutines
@Composable
fun BlockFreeUIThroughCoroutines(
modifier: Modifier = Modifier
) {
val scope = rememberCoroutineScope()
LazyColumn(
modifier = modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(10.dp),
contentPadding = PaddingValues(16.dp)
) {
item {
Button(onClick = {
scope.launch {
delay(5000)
}
}) {
Text(text = "Click")…