viewModelScope

Prerequisites:

使用時機

ViewModel 中的資料操作:

  • API 呼叫
  • 資料庫操作
  • 商業邏輯

當 ViewModel 結束時自動清除協程,不會記憶體洩露。

1
2
3
4
5
6
7
8
9
10
11
12
package com.example.coroutine.api
import retrofit2.http.GET

interface ArticleApi {
  @GET("article/list")
  suspend fun articleList(): ArticleList
  companion object {
    val retrofit: ArticleApi by lazy {
      RetrofitUtil.createService(ArticleApi::class.java)
    }
  }
}
1
2
3
4
5
6
7
8
9
10
class ArticleViewModel : ViewModel() {
  val _articleList = MutableStateFlow<ArticleList?>(null)
  val articleList: StateFlow<ArticleList?> = _articleList
  fun getArticleList() {
    viewModelScope.launch {
      val result = ArticleApi.retrofit.articleList()
      _articleList.value = result
    }
  }
}

results matching ""

    No results matching ""