single and factory
- Kotlin course
- Advanced
- Lesson 39/83
- 5 min
Learn binding types with single and factory.
single and factory
single and factory are the two Koin declarations that set a dependency's lifetime. single returns one instance; factory returns a new instance each time.
Example: single { Repository() } returns the same Repository throughout the app. factory { Service() } creates a new Service on each call. single suits stateful objects; factory suits lightweight, independent ones. The wrong choice can lead to memory leaks or unnecessary recreation.
When single, when factory?
If a dependency holds state and is shared across the app, choose single. For example, a database connection, session data.
For lightweight, independent, short lived objects, factory fits. For example, a fresh view model per request, a new request object per click. Using single wrongly lets dependencies affect each other; using factory wrongly creates memory overhead. The choice depends on the nature of the dependency.
Practice Define Repository with single
Define val appModule = module { single { Repository() } }. Also define class Repository. Inside main, print println("Single ready").
Starter code
// single and factory
// write here
import org.koin.dsl.module
fun main() {
}Sample solution
class Repository
val appModule = module {
single { Repository() }
}
fun main() {
println("Single ready")
}Expected output
Single ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match single and factory
| Term | Meaning |
|---|---|
single |
Singleton |
factory |
New each time |
module |
Dependency block |
get |
Another dependency |
2 Which suits a database connection?
- factory
- single Correct answer
- neither
- both
Explanation: A database connection is a singleton with single.
3 Complete the single call
val appModule = module {
____ { Repository() }
}
val appModule = module {
single { Repository() }
}
Explanation: single declares a singleton.