Skip to content

Commit

Permalink
Update docs to explain about using an OnContextAvailableListener.
Browse files Browse the repository at this point in the history
Fixes #4232.

RELNOTES=n/a
PiperOrigin-RevId: 610451925
  • Loading branch information
Chang-Eric authored and Dagger Team committed Feb 26, 2024
1 parent 72950fa commit aa86dec
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
14 changes: 8 additions & 6 deletions dev-guide/android.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,12 +311,14 @@ calls `AndroidInjection.inject()` immediately in `onCreate()`, before calling
`super.onCreate()`, and `DaggerFragment` does the same in `onAttach()`, which
also prevents inconsistencies if the `Fragment` is reattached.

It is crucial to call `AndroidInjection.inject()` before `super.onCreate()` in
an `Activity`, since the call to `super` attaches `Fragment`s from the previous
activity instance during configuration change, which in turn injects the
`Fragment`s. In order for the `Fragment` injection to succeed, the `Activity`
must already be injected. For users of [ErrorProne], it is a
compiler error to call `AndroidInjection.inject()` after `super.onCreate()`.
It is crucial to call `AndroidInjection.inject()` before fragments from the
previous activity instance during configuration change are restored, in case any
injected members on the Fragment rely on methods in the activity that may use
injected members in the activity. Often this can be done by injecting before
calling `super.onCreate`, but this can also be achieved by registering an
[`OnContextAvailableListener`](https://developer.android.com/reference/kotlin/androidx/activity/contextaware/OnContextAvailableListener).
For users of [ErrorProne], it is a compiler error to call
`AndroidInjection.inject()` after `super.onCreate()`.

## FAQ

Expand Down
9 changes: 9 additions & 0 deletions hilt/optional-inject.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,12 @@ class MyFragment : Fragment() {
}
```
{: .c-codeselector__code .c-codeselector__code_kotlin }

Note that for activities, because Hilt injection is usually run as a part of
`super.onCreate()` and it is recommended to do your own injection before
fragments are restored which also happens during `super.onCreate()`, you likely
need to use an
[`OnContextAvailableListener`](https://developer.android.com/reference/kotlin/androidx/activity/contextaware/OnContextAvailableListener)
to run your non-Hilt injection code. Hilt uses the same listener under the hood,
so then the order would be Hilt's `OnContextAvailableListener` would run,
then yours, then fragments would be restored.

0 comments on commit aa86dec

Please sign in to comment.