Junior — Middle
Explain the mechanism of ViewModel delegates and how they interact with the rest of the application architecture.
sobes.tech AI
Answer from AI
ViewModel delegates are interfaces or objects through which the ViewModel passes events or commands to the View (Activity/Fragment) without a direct dependency.
Working mechanism:
- The ViewModel contains the UI logic and state.
- To interact with the View, it uses delegates — interfaces with callback methods.
- The View implements these interfaces and passes its implementation to the ViewModel.
- When an event occurs in the ViewModel (e.g., navigation or message display), it calls the delegate method.
This helps to separate responsibilities and make the architecture cleaner, as the ViewModel does not depend directly on a specific View implementation.
Example:
interface ViewDelegate {
fun showError(message: String)
fun navigateToDetails(id: Int)
}
class MyViewModel : ViewModel() {
var delegate: ViewDelegate? = null
fun onButtonClicked() {
// Some logic
if (error) {
delegate?.showError("Loading error")
} else {
delegate?.navigateToDetails(42)
}
}
}
// In Activity or Fragment
class MyActivity : AppCompatActivity(), ViewDelegate {
private val viewModel = MyViewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.delegate = this
}
override fun showError(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
override fun navigateToDetails(id: Int) {
// Navigation
}
}