Coroutine with basic interview questions?

Duggu
3 min readOct 12, 2023

What is Kotlin Coroutines?

Kotlin Coroutines is a concurrency design pattern introduced by JetBrains for the Kotlin programming language. It provides a way to write asynchronous code that looks and behaves like synchronous code, using the concept of “suspending” functions.

Why do we need Kotlin Coroutines?

  1. Simplified Asynchronous Code: Traditionally, async programming models like callbacks, futures, and promises can lead to “callback hell” or deeply nested structures. Coroutines simplify this with linear-looking code.
  2. Lightweight: Coroutines are lightweight compared to threads. You can launch thousands of them, and they won’t bring your system to a halt.
  3. Flexible Flow Control: They offer better flow control using suspend functions, allowing you to decide when to pause and resume work.
  4. Integration with Kotlin Flow: For reactive-style streams, Kotlin introduced Flow which integrates seamlessly with coroutines.

Integration of Kotlin Coroutines in Android:

Add Dependency: To use coroutines in your Android project, you’d need to add the necessary dependencies:

implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2" 
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2"

Using in ViewModel: For Android, ViewModel can be integrated with coroutines to handle background tasks. For instance:

class MyViewModel : ViewModel() {
private val viewModelJob = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
fun fetchData() {
uiScope.launch {
// make network or database call
}
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
}

15 Interview Questions on Kotlin Coroutines with Examples:

What is a suspending function?
A suspending function is a function that can be paused and resumed at a later time. They can execute a long running operation and wait for it to complete without blocking.

How do you launch a coroutine?

CoroutineScope(Dispatchers.Main).launch {     
// Your code here
}

Explain the difference between launch and async.

Both are used to launch coroutines but launch is used when you don’t need a result back whereas async is used when you need a result.

What are dispatchers in coroutines?

Dispatchers determine what thread or threads the coroutine uses. Common dispatchers are Main, IO, Default, and Unconfined.

How do you handle exceptions in coroutines?

You can use the CoroutineExceptionHandler or wrap your code in a try-catch block within the coroutine.

What is a Job in coroutines?

A Job represents a cancellable piece of work. It has a lifecycle and can be cancelled.

How do you cancel a coroutine?

val job = launch {
// some code
} job.cancel()

What is withContext? Give an example.

suspend fun fetchData() {
withContext(Dispatchers.IO) {
// fetch data
}
}

withContext is used to switch the context of a coroutine.

How is delay different from Thread.sleep?

delay is a suspending function that doesn't block the thread, whereas Thread.sleep blocks the thread.

What is Flow in Kotlin?

Flow is a cold stream of asynchronous values. It integrates with coroutines and can produce values over time.

How do you convert a callback-based API to use coroutines?

You can wrap the callback using suspendCoroutine or callbackFlow.

What is the purpose of suspendCancellableCoroutine?

It's a suspending function that can be cancelled. If the coroutine is cancelled, the provided block is executed.

How do you ensure a coroutine is run on the main thread in Android?

CoroutineScope(Dispatchers.Main).launch {
// Your code here
}

How would you run a piece of coroutine code periodically?

CoroutineScope(Dispatchers.Main).launch {
while(isActive) {
// Do something
delay(timeInMillis)
}
}

What is coroutineScope vs CoroutineScope?

coroutineScope is a suspending function that creates a new scope and doesn't complete until all launched children do. CoroutineScope is an interface that can be used to launch coroutines.

Above answers provide a general overview, always be prepared for follow-up questions during an interview.

Perhaps my article will offer some clarity. If you find it valuable, please consider following and applauding. Your support will inspire me to write more articles like this.

#kotlin #kotlindeveloper #android #androiddeveloper #softwaredevelopment #androiddevelopment #kotlinandroid #developers #developercommunity #softwareengineer #googledevs #googlegroups #androidgroups #googleandroid #gradle #gradleandroid #community #linkedinforcreators #creators #linkedin #linkedinlearning #linkedinfamily #linkedinconnections #Coroutines

--

--