0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Android:LiveData LifecycleOwnerの注意事項!

Posted at

はじめに

FragmentでLiveData#observeメソッドを使う際の注意事項について記載する。
アプリがクラッシュしたり予期せぬ動作になる可能性があるため、注意が必要。

注意事項

FragmentでLiveData#observeメソッドを使う際は、引数にviewLifecycleOwnerを使用した方が良い。

理由は以下の通り:

  1. メモリリークの防止:
    viewLifecycleOwnerを使用することで、Fragmentのビューが破棄されたときに自動的にObserverが解除されます。

  2. 多重生成の回避:
    thisを使用すると、Fragmentが再作成されるたびに新しいObserverが追加され、同じイベントに対して複数回反応する可能性があります。

  3. ビューのライフサイクルに合わせた適切な管理:
    viewLifecycleOwnerはFragmentのビューのライフサイクルに紐づいているため、onCreateView()からonDestroyView()までの間でのみObserverが有効になります。

使用例:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    viewModel.liveData.observe(viewLifecycleOwner) { data ->
        // データの更新処理など
    }
}

この方法を使用することで、Fragmentのビューが破棄されても適切に停止され、不要な処理や潜在的なバグを防ぐことができます。


参考資料
 https://qiita.com/sdkei/items/100580137e7b2f705205
 https://qiita.com/d_forest/items/6b411c9e8093e8a1f5ae

以上

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?