Skip to content

Instantly share code, notes, and snippets.

@qureshiayaz29
Created October 4, 2025 09:19
Show Gist options
  • Select an option

  • Save qureshiayaz29/774742f852cabf590257a75b89ebf3f8 to your computer and use it in GitHub Desktop.

Select an option

Save qureshiayaz29/774742f852cabf590257a75b89ebf3f8 to your computer and use it in GitHub Desktop.
// UserViewModel.kt
class UserViewModel(private val repository: UserRepository) : ViewModel() {
private val _users = MutableLiveData<Resource<List<User>>>()
val users: LiveData<Resource<List<User>>> = _users
fun loadUsers() {
viewModelScope.launch {
_users.value = Resource.Loading()
_users.value = repository.getUsers()
}
}
}
// UserRepository.kt
class UserRepository(private val apiService: ApiService) {
suspend fun getUsers(): Resource<List<User>> {
return try {
Resource.Success(apiService.getUsers())
} catch (e: Exception) {
Resource.Error(e.message ?: "Unknown error")
}
}
}
// MainActivity.kt
class MainActivity : AppCompatActivity() {
private val viewModel: UserViewModel by viewModels()
private lateinit var adapter: UserAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setupRecyclerView()
observeViewModel()
viewModel.loadUsers()
}
private fun observeViewModel() {
viewModel.users.observe(this) { resource ->
when (resource) {
is Resource.Loading -> showLoading()
is Resource.Success -> adapter.submitList(resource.data)
is Resource.Error -> showError(resource.message)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment