Sean McQuillan [G]
06/29/2020, 6:40 PM@Composable
fun <T> koinInject(): T {
val context = KoinContext.get() // this won't recompose if KoinContext is changable, if that is so this should become an Ambient
return remember(context) { context.inject() } // inject only called once per component per context (but doesn't trigger recomposition when context changes)
}
Wanted to post it here to see what the requirements are. Code like this would make it behave similarly to a member variable.arnaud.giuliani
06/30/2020, 1:23 PMarnaud.giuliani
06/30/2020, 1:23 PMarnaud.giuliani
06/30/2020, 1:28 PMinject
?henrikhorbovyi
06/30/2020, 2:25 PMhenrikhorbovyi
06/30/2020, 2:32 PMKoinContext
henrikhorbovyi
06/30/2020, 2:33 PMhenrikhorbovyi
06/30/2020, 3:27 PMinject
would be a better name as well @arnaud.giuliani.
It'd follow the same names as Koin already has.kenkyee
07/01/2020, 10:52 AMarnaud.giuliani
07/01/2020, 4:09 PMarnaud.giuliani
07/01/2020, 4:09 PMSean McQuillan [G]
07/01/2020, 7:18 PMPreview
.
One might think to call startKoin in the Preview
, but I wouldn't recommend that today as we make no gurantees about only running one Preview
at a time in the same AS process.
🤔Sean McQuillan [G]
07/01/2020, 7:30 PMApplication
onCreate
is correct even in a compose application given the global context behavior.
I need to think more about trying to use this in Preview. For now my advise would be to hoist inject
from components that you want to @Preview
(or test) up a level:
@Composable
fun UsesDependency() {
val user: UserManager by inject()
// ...
}
// transforms to
@Composable
fun DisplayUser() {
val user: UserManager by inject()
DisplayUser(inject())
}
@Composable
fun DisplayUser(user: UserManager) {
// ..
}
Sean McQuillan [G]
07/01/2020, 8:32 PMSean McQuillan [G]
07/09/2020, 6:48 PM@Composable
fun UsesDependency(manager: UserManager = inject()) {
// this allows caller to bypass the service locator and inject custom values
}
Following this pattern would allow you to bypass the inject()
call when calling from @Preview
. Worth sharing in case it helps you with your code @kenkyeekenkyee
07/10/2020, 12:05 AMSean McQuillan [G]
07/10/2020, 5:54 PM