Mastering Android Kotlin: Junior vs Mid vs Senior — Practical Code Examples
Loading Data in a Fragment Scenario: Load and display user data from a ViewModel. lifecycleScope.launchWhenStarted { viewModel.userData .filterNotNull() .collect { user -> textView.text = user.name } } Making a Network Request with Retrofit Scenario: Fetch user data from an API using Retrofit lifecycleScope.launch { runCatching { api.getUser() } .onSuccess { user -> textView.text = user.name } .onFailure { error -> // Handle error } } Handling Button Clicks Scenario: Respond to a button click event. button.setOnClickListener { context?.let { Toast.makeText(it, "Clicked", Toast.LENGTH_SHORT).show() } } Navigating Between Fragments Scenario: Navigate from one fragment to another using Navigation Component. val action = FirstFragmentDirections.actionFirstFragmentToSecondFragment() findNavController().navigate(action) Displaying a List with RecyclerView Scenario: Display a list of items using RecyclerView. val adapter = MyAdapter().apply { submitList(items) } recyclerView.adapter = adapter

- Loading Data in a Fragment Scenario: Load and display user data from a ViewModel.
lifecycleScope.launchWhenStarted {
viewModel.userData
.filterNotNull()
.collect { user ->
textView.text = user.name
}
}
- Making a Network Request with Retrofit Scenario: Fetch user data from an API using Retrofit
lifecycleScope.launch {
runCatching { api.getUser() }
.onSuccess { user ->
textView.text = user.name
}
.onFailure { error ->
// Handle error
}
}
- Handling Button Clicks Scenario: Respond to a button click event.
button.setOnClickListener {
context?.let {
Toast.makeText(it, "Clicked", Toast.LENGTH_SHORT).show()
}
}
- Navigating Between Fragments Scenario: Navigate from one fragment to another using Navigation Component.
val action = FirstFragmentDirections.actionFirstFragmentToSecondFragment()
findNavController().navigate(action)
- Displaying a List with RecyclerView Scenario: Display a list of items using RecyclerView.
val adapter = MyAdapter().apply {
submitList(items)
}
recyclerView.adapter = adapter