Skip to content

Instantly share code, notes, and snippets.

@aartikov
Created January 10, 2023 21:45
Show Gist options
  • Save aartikov/30e182fd58ed9697af498bb22ef4edfa to your computer and use it in GitHub Desktop.
Save aartikov/30e182fd58ed9697af498bb22ef4edfa to your computer and use it in GitHub Desktop.
Decompose DI
class App : Application(), KoinProvider {
override lateinit var koin: Koin
private set
override fun onCreate() {
super.onCreate()
koin = createKoin()
}
private fun createKoin(): Koin {
return Koin().apply {
loadModules(allModules)
declare(this@App as Application)
declare(this@App as Context)
declare(ComponentFactory(this))
createEagerInstances()
}
}
}
/**
* Used to create Decompose components. Creation of components are implemented as extension functions.
*/
class ComponentFactory(private val localKoin: Koin) : KoinComponent {
override fun getKoin(): Koin = localKoin
}
val mainModule = module {
single { SomeDependency1() }
single { SomeDependency2() }
single { SomeDependency3() }
}
fun ComponentFactory.createMainComponent(
componentContext: ComponentContext
): MainComponent {
return RealMainComponent(componentContext, get())
}
fun ComponentFactory.createFeedbackComponent(
componentContext: ComponentContext,
onPositiveFeedbackGiven: () -> Unit
): FeedbackComponent {
return RealFeedbackComponent(componentContext, onPositiveFeedbackGiven, get(), get())
}
fun ComponentFactory.createTheoryComponent(
componentContext: ComponentContext
): TheoryComponent {
return RealTheoryComponent(componentContext, get(), get())
}
interface KoinProvider {
val koin: Koin
}
val Application.koin get() = (this as KoinProvider).koin
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val componentFactory = application.koin.get<ComponentFactory>()
val mainComponent = componentFactory.createMainComponent(defaultComponentContext())
setContent {
AppTheme {
MainUi(mainComponent)
}
}
}
}
class RealMainComponent(
componentContext: ComponentContext,
componentFactory: ComponentFactory
) : ComponentContext by componentContext, MainComponent {
override val theoryComponent = componentFactory.createTheoryComponent(
childContext(key = "theory")
)
override val feedbackComponent = componentFactory.createFeedbackComponent(
childContext(key = "feedback"),
onPositiveFeedbackGiven = {
theoryComponent.unlockBonusTheoryMaterial()
}
)
}
@Drabu
Copy link

Drabu commented Apr 4, 2024

How do we set this up in iOS MainViewController?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment