Calling inject() extension within @Composable functions
See original GitHub issuePlaying around with Koin + Jetpack Compose, I would like to inject a dependency within a @Composable
function.
@Composable
fun AppContent() {
val newsRepository: NewsRepository by inject() // <~ it does not copile
NewsScreen(newsRepository)
}
In this case, you get an error, because inject is an extension on KoinComponent
, and there is no KoinComponent
in this scope.
So, I thought about a @Composable
function that provides a KoinComponent
scope.
object InjectableComponent : KoinComponent
@Composable
fun Injectable(child: @Composable InjectableComponent.() -> Unit) {
child(InjectableComponent)
}
Using this @Composable
would be like this:
@Composable
fun AppContent() {
Injectable {
val newsRepository: NewsRepository by inject()
NewsScreen(newsRepository)
}
}
I’d like to discuss this topic and hear opinions from you all
Issue Analytics
- State:
- Created 3 years ago
- Comments:10 (4 by maintainers)
Top Results From Across the Web
Compose and other libraries - Android Developers
Hilt is the recommended solution for dependency injection in Android apps, and works seamlessly with Compose. The viewModel() function mentioned in the ...
Read more >Dependency injection inside extension function - Stack Overflow
I use my app component to inject into extension methods. For example, to use MyInjectableClass in an extension method:
Read more >Navigating through multi-module Jetpack Compose applications
Jetpack Compose, navigation, multi-module architecture, ... Inside, it calls another function called Composable (first letter capital).
Read more >Android Compose UI: ViewModel + Hilt Dependency Injection
Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project.
Read more >Ruleset - Twitter Jetpack Compose Rules
To solve this problem, you should inject these dependencies as default values in the composable function. Let's see it with an example. @Composable...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
KoinContextHandler
is the context handler, that help us prepare the land for Kotlin MP & otehr Koin context handling strategies.GlobalContext
is not accessible anymore I guess 🤔We have started to speak about a compose project for Koin on #koin-dev
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.