31. Explain withContext() function in Kotlin coroutines
In Kotlin Coroutines, withContext() is a suspending function used to switch the coroutine context (i.e., the thread or dispatcher) in a safe, concise, and structured way.
Syntax
suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T
32. Difference Between launch, async, and withContext
Feature | launch | async | withContext |
---|---|---|---|
Returns | Job (no result) | Deferred<T> (future) | T (direct result) |
Use Case | Fire-and-forget | Concurrent result | Context switch + result |
Suspension | No | No (until await()) | Yes |
Lightweight? | Yes | Yes | Yes |
33. Explain flow in Kotlin coroutines .
In Kotlin, Flow is a part of the Kotlin Coroutines library and represents a cold asynchronous data stream that can emit multiple values sequentially.
Basic Flow Structure
fun getNumbers(): Flow<Int> = flow {
for (i in 1..5) {
delay(1000) // simulate some work
emit(i) // emit value
}
}
Key Flow Operators
Operator | Description |
---|---|
map | Transforms each emitted value |
filter | Filters emitted values |
take(n) | Takes only first n values |
collect | Terminal operator to consume values |
onEach | Side effects like logging |
catch | Handle exceptions |
flowOn | Change the CoroutineDispatcher |
Types of Flows
Flow Type | Description |
---|---|
Flow | Cold stream |
SharedFlow | Hot, broadcast to multiple collectors |
StateFlow | Hot, holds a single state value |
Channel | Coroutine-friendly message pipe |
34. Explain hot and cold streams.
In Kotlin's Flow API, the concepts of hot and cold streams describe how data producers behave in relation to their consumers. These concepts are critical for building reactive, efficient, and predictable asynchronous programs.
A cold stream is lazy — it starts emitting data only when there is a collector. Each collector gets its own stream of emissions.
Example:
val coldFlow = flow {
println("Flow started")
emit("Hello")
emit("World")
}
runBlocking {
coldFlow.collect { println("Collector 1: $it") }
coldFlow.collect { println("Collector 2: $it") }
}
Flow started
Collector 1: Hello
Collector 1: World
Flow started
Collector 2: Hello
Collector 2: World
A hot stream emits values regardless of collectors. Collectors may miss data if they subscribe late.
val hotFlow = MutableSharedFlow<String>()
// Emitting in a coroutine
GlobalScope.launch {
hotFlow.emit("🔥 Event 1")
delay(100)
hotFlow.emit("🔥 Event 2")
}
// Collecting later
runBlocking {
delay(200)
hotFlow.collect {
println("Collector received: $it")
}
}
May be nothing or only Event 2, depending on timing.
Cold vs Hot Flow in Kotlin
Feature | Cold Flow (flow) | Hot Flow (SharedFlow, StateFlow) |
---|---|---|
Starts on collect? | ✅ Yes | ❌ No (emits always) |
Collector gets all? | ✅ Yes | ❌ Might miss emissions |
Shared by collectors? | ❌ No (isolated) | ✅ Yes (shared across collectors) |
Memory efficient? | ✅ | ❌ (can buffer or cache values) |
Use case | API, database, calculations | UI events, sockets, real-time data |
35. What is StateFlow in Kotlin?
StateFlow is a state-holder observable flow introduced in Kotlin Coroutines. It is a part of the kotlinx.coroutines.flow library and is a cold flow that always holds the latest emitted value, just like LiveData in Android, but more powerful and flexible.
Key Concepts of StateFlow
Feature | Description |
---|---|
Hot Flow | Keeps emitting values even if there are no collectors (unlike regular Flow). |
State Holder | Always contains the latest state value. |
Replay Behavior | Emits the current state value to new collectors immediately. |
Lifecycle-Aware (UI) | Can be used with collectAsState() in Jetpack Compose. |
Basic Declaration
private val _counter = MutableStateFlow(0) // Mutable (for internal updates)
val counter: StateFlow<Int> = _counter // Read-only exposed to external use
36. StateFlow vs LiveData
Feature | StateFlow | LiveData |
---|---|---|
Lifecycle-aware | ❌ (Needs manual handling) | ✅ (Built-in lifecycle) |
Kotlin Native | ✅ (Works everywhere) | ❌ (Android only) |
Thread Safety | ✅ | ✅ |
Backpressure | ✅ | ❌ |
Jetpack Compose | ✅ (collectAsState) | ✅ (observeAsState) |