39
19

More than 1 year has passed since last update.

onResume などのライフサイクルメソッドのオーバーライドが非推奨になっていた件

Last updated at Posted at 2022-10-28

Recommendations for Android architecture 」の一文に次が書いてありました。

Lifecycle
Do not override lifecycle methods such as onResume in Activities or Fragments. Use LifecycleObserver instead. If the app needs to perform work when the lifecycle reaches a certain Lifecycle.State, use the repeatOnLifecycle API.

そもそも onResume はAndroidにおける主要なライフサイクルの1つ、他にも onCreateonStart といったものもあり、今回このライフサイクル系メソッドのオーバーライドが基本非推奨( Strongly recommended )になった。

そもそもなんで非推奨になったの?

上記の1文では「オーバーライドしないでください。 LifecycleObserver を代わりに使ってください。」と書いてある。

つまりこれまで次のように記述していた部分が非推奨となり、

override fun onResume() {
    super.onResume()
    textview.text = "hoge"
}

サンプルにあるように LifecycleObserver を使ってライフサイクルの状態における変更を受け取るようなカタチになるらしい。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    viewLifecycleOwner.lifecycle.addObserver(object: DefaultLifecycleObserver {
        override fun onResume(owner: LifecycleOwner) {
            textview.text = "hoge"
        }
    }
}

そもそもなぜ Observer を使うのか?

Handling Lifecycles with Lifecycle-Aware Components 」には次が書いてありました。

Moreover, there's no guarantee that the component starts before the activity or fragment is stopped. This is especially true if we need to perform a long-running operation, such as some configuration check in onStart(). This can cause a race condition where the onStop() method finishes before the onStart(), keeping the component alive longer than it's needed.

つまりコンポーネントが開始する前にアクティビティやフラグメントが停止する可能性やコンポーネントの競合状態が発生すると、必要以上に長い間稼働し続けることになるらしい。

つまり次のようなサンプルだと、状態の変化次第で本来の想定(画面を閉じる)とは逆の onStop -> onStart の順で呼ばれた場合 myLocationListener.start() が実行され続けてしまうからです。

public override fun onStart() {
    super.onStart()
    myLocationListener.start()
    // manage other components that need to respond
    // to the activity lifecycle
}

public override fun onStop() {
    super.onStop()
    myLocationListener.stop()
    // manage other components that need to respond
    // to the activity lifecycle
}

そのため LifecycleObserver を代わりに使うことで、上記の問題を解決するために推奨されたのだと理解しました。

以上です。
別の考察大歓迎なのでコメントください。

39
19
2

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
39
19