0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

lifecycleScopeとviewModelScopeの違い

Posted at

CoroutineScopeの種類であるlifecycleScopeviewModelScope の違いを仕組みと使いどころの点を整理してメモします。

まずは CoroutineScope の基本

CoroutineScope は、Kotlin のコルーチンを管理する「ライフサイクル付きの領域」です。
どのスコープで起動するかによって、キャンセルのタイミングや責務の範囲が変わります。

CoroutineScope(Dispatchers.Main).launch {
    // UIスレッドで実行される
}

lifecycleScope とは

lifecycleScope は、Activity や Fragment に紐づいた CoroutineScope で、ライフサイクルに合わせてコルーチンが自動的にキャンセルされます。たとえば、Fragment の表示中に一時的な UI 更新を行いたい場合に便利です。

  • Activity や Fragment の UI が表示されている間だけ動かしたい処理
  • アニメーションや短時間の表示更新などの一時的な処理

といった用途に適しています。

lifecycleScope.launch {
    // View が表示されている間だけ動く
}

viewModelScope とは

viewModelScope は、ViewModel に紐づいた CoroutineScope で、ViewModel が破棄されるまでスコープが維持されます。このスコープは、UI のライフサイクルとは独立して動作するため、 画面回転などで Activity や Fragment が再生成されても処理が継続されます。データの取得や保存、非同期処理など、UI に依存しないロジックを実行するのに向いています。
viewModelScope を使うことで、データ処理を安全に管理できます。UI が一時的に消えても、バックグラウンドでデータをロードし続け、再表示時に最新の状態を反映させることが可能です。

class SampleViewModel : ViewModel() {

    fun fetchData() {
        viewModelScope.launch {
            val data = repository.load()
            // LiveDataやStateFlowでUIへ通知
        }
    }
}

まとめ

  • UIに関わる処理 → lifecycleScope
  • データの取得や永続的な処理 → viewModelScope
  • FragmentでUI操作を行う場合 → viewLifecycleOwner.lifecycleScope

これらを意識して使い分けることで、ライフサイクルに沿った安全で保守性の高いコードを書くことができます。

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?