Android runs all UI on the main thread. Any blocking call — network request, database query, file read — freezes the UI. If blocked for more than 5 seconds, Android shows an ANR (Application Not Responding) dialog.
// Launch a coroutine in ViewModel scope viewModelScope.launch { // Switch to IO thread for network/DB work val users = withContext(Dispatchers.IO) { api.fetchUsers() } // Automatically back on Main thread — update UI _users.value = users }
suspend fun loadProfile(id: String): Profile { val user = withContext(Dispatchers.IO) { db.getUser(id) } val posts = withContext(Dispatchers.IO) { api.getPosts(id) } return Profile(user, posts) } // Parallel execution — both requests run concurrently suspend fun loadDashboard() = coroutineScope { val news = async { api.getNews() } val weather = async { api.getWeather() } Dashboard(news.await(), weather.await()) }
private async void LoadDataAsync() { IsBusy = true; var users = await Task.Run(() => _db.GetAllUsers()); Users = new ObservableCollection<User>(users); IsBusy = false; }