Created
October 4, 2025 09:19
-
-
Save qureshiayaz29/774742f852cabf590257a75b89ebf3f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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