0Pricing
Jetpack Compose Academy · درس

استدعاءات suspend في ViewModel

اجلب البيانات خارج الخيط الرئيسي

استدعاءات suspend في ViewModel درس مجاني في Jetpack Compose Academy على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Jetpack Compose Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Jetpack Compose Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Never Block the Main Thread

Network calls take time, and doing them on the UI thread freezes your app. You move that work off the main thread instead.

Make the Endpoint suspend

Mark your Retrofit function with the suspend keyword. Now it returns the parsed result directly and can pause without blocking. ⏸️

@GET("users")
suspend fun getUsers(): List<User>

The ViewModel Owns the Logic

Fetching data belongs in the ViewModel, not the Composable. It survives rotation and keeps your UI code purely about display.

class UserViewModel : ViewModel() {
    // network logic lives here
}

Launch With viewModelScope

A suspend function needs a coroutine. viewModelScope gives you one that is cancelled automatically when the ViewModel clears.

viewModelScope.launch {
    val users = api.getUsers()
}

Store the Result in State

Once the call returns, save the data into a state property so Compose can observe it and redraw the screen.

var users by mutableStateOf<List<User>>(emptyList())

Wrap It In a try-catch

Networks fail, so guard the call with try-catch. An unhandled exception in a coroutine can crash your whole app.

try {
    users = api.getUsers()
} catch (e: Exception) {
    // handle failure
}

Fetch on Init

Trigger the first load in the ViewModel's init block, so data starts arriving the moment the screen is created.

init {
    loadUsers()
}

Keep It in a Function

Wrap the fetch in a named function like loadUsers. That makes it easy to call again for retry or pull-to-refresh.

fun loadUsers() = viewModelScope.launch {
    users = api.getUsers()
}

Dispatchers Handle Threading

Retrofit already runs the request on a background dispatcher, so you usually don't switch threads with Dispatchers.IO yourself.

Collect State in Compose

In your Composable, read the ViewModel's state. Because it's observable, Compose recomposes the instant fresh data lands.

val users = viewModel.users

Cancellation Is Automatic

If the user leaves and the ViewModel clears, viewModelScope cancels the in-flight call, so you waste no work on a dead screen.

Quick Check

Which scope cancels its coroutines automatically when the ViewModel is cleared?

Recap: Calling From the ViewModel

You made endpoints suspend, launched them in viewModelScope, stored results in state, and caught errors. Next you'll render loading, success, and error states.

الأسئلة الشائعة

هل درس «استدعاءات suspend في ViewModel» مجاني؟

نعم — نص درس «استدعاءات suspend في ViewModel» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Jetpack Compose Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Jetpack Compose Academy 4 دروس في المجموع.

ماذا ستتعلم في «استدعاءات suspend في ViewModel»؟

اجلب البيانات خارج الخيط الرئيسي تتمرن على Jetpack Compose Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Jetpack Compose Academy؟

لا تُشترط خبرة سابقة. Jetpack Compose Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «استدعاءات suspend في ViewModel»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Jetpack Compose Academy هذا؟

نعم. كل درس في Jetpack Compose Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تعريف واجهة Retrofit API
  2. تحليل JSON باستخدام Moshi
  3. استدعاءات suspend في ViewModel
  4. واجهة التحميل والنجاح والخطأ
← العودة إلى Jetpack Compose Academy