Organizing Koin modules

m0skit0
2 min readJan 5, 2020

--

If you have ever used Koin in a medium-sized project, you know that your typical Koin modules start growing ever bigger. If you have named injections as well, it’s even worse. Your Koin module definition file starts to be hundreds of lines big and pretty unreadable. So how we can refactor this?

Koin modules for a very very simple app with one use case and one view, already ~50 LoC

Good: one file per module

The simplest refactor is to move each module to its own file:

However we still have some problems with this approach:

  • If we have a lot of named, browsing through them is a PITA, even using the IDE code completion.
  • Named names should be unique across ALL modules to avoid confusion, and to avoid compilation errors if all of these files belong to the same package (which is usually the case).
  • We need to remember the name of each module property.

Better: KoinModuleProvider interface

Enter interfaces: we define an interface with a function that returns a Koin module. For example:

Now we can have some fun (pun intended):

This interface solves the 3 problems mentioned before:

  • Browsing the named is per object now, so we can easily reduce the number of code completion results, as well as knowing to which layer of our application this particular named belongs to.
  • Named do not have to be unique across all the modules, only in that specific module. However I do recommend you keep the names unique to avoid potential confusions.
  • We do not need to remember which modules are declared where, because thanks to the IDE we can simply ask which classes implement the KoinModuleProvider interface.

Of course this solution adds a little more code to load the modules into Koin:

I hope you found this article useful and as always I’m very interested in your opinions!

--

--