37. What is LiveData in Kotlin?
LiveData is a lifecycle-aware observable data holder class used in Android development with Kotlin (and Java). It’s part of Android Jetpack's Architecture Components.
LiveData is used to observe data changes in a way that respects the lifecycle of UI components (e.g., Activity, Fragment), so that:
Basic Example
1. ViewModel with LiveData
class MyViewModel : ViewModel() {
private val _counter = MutableLiveData<Int>()
val counter: LiveData<Int> get() = _counter
fun increment() {
_counter.value = (_counter.value ?: 0) + 1
}
}
2. Fragment observing LiveData
class MyFragment : Fragment() {
private val viewModel: MyViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewModel.counter.observe(viewLifecycleOwner) { count ->
textView.text = "Count: $count"
}
button.setOnClickListener {
viewModel.increment()
}
}
}
Use LiveData when:
38. Describe the scope function “apply” in Kotlin.
In Kotlin, the apply scope function is used to configure an object. It allows you to access the object using this and returns the object itself.
Syntax
val obj = MyClass().apply {
property1 = "value"
property2 = 42
doSomething()
}
Equivalent to:
val obj = MyClass()
obj.property1 = "value"
obj.property2 = 42
obj.doSomething()
39. Describe the scope function “run” in Kotlin.
In Kotlin, the run scope function is used to execute a block of code within the context of an object or as a standalone block, returning the last expression's result.
run :
Property | Value |
---|---|
Object Reference | this (implicit) |
Return Value | Last expression result |
Common Use Cases | Object configuration, null checks, computed results |
Syntax:
1. As an object extension
val result = "Hello".run {
println(length)
length * 2
}
// result = 10
Here:
2. As a standalone block (no object)
val result = run {
val a = 5
val b = 10
a + b
}
// result = 15
Used like a lambda to group and return a computed value.
run is great when you want to use an object and compute a result or group a block of expressions into a single return value.
40. Comparison between Scope Functions .
Function | Context Object | Returns | Use For |
---|---|---|---|
apply | this | object | Configure object |
also | it | object | Add side effects (logging, etc.) |
let | it | result value | Transform and chain |
run | this | result value | Do operation and return result |
with | this | result value | Same as run, but not extension |