개발/안드로이드 개발
(Koin) BroadcastReceiver에서 inject()를 사용할 수 없는 문제
룬아님
2019. 10. 24. 16:04
분명 Activity와 Service 등에서 inject()를 사용하여 koin을 잘 사용하였는데
BroadcastReceiver를 상속받은 클래스에서 inject()를 찾을 수 없다고 하여서 검색을 해보았다.
결론은 클래스에 KoinComponent를 상속하여 해결할 수 있다.
보통 생명주기를 가지는 activity, service 등은 Koin에서 extension으로 구현하고 있기 때문에 따로 KoinComponent를 상속하지 않아도사용할 수 있지만 다른 요소는 기본적으로 지원하고 있지 않기 때문이다.
// In Activity no need for KoinComponent
class SomeActivity: AppCompatActivity() {
// evaluates dependency eagerly
val service: SomeOtherService = get()
// evaluates dependency lazily
val lazyService: SomeLazyService by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ... other required stuff
// does something with services
}
}
// In non-lifecycle component, KoinComponent is needed
class SomeBroadcastReceiver: BroadcastReceiver(), KoinComponent {
// evaluates dependency eagerly
val service: SomeOtherService = get()
// evaluates dependency lazily
val lazyService: SomeLazyService by inject()
override fun onReceive(context: Context?, intent: Intent?) {
// does something with services
}
}
출처 : https://android.jlelse.eu/koin-simple-android-di-a47827a707ce
Koin - Simple Android DI
Dealing with dependency injection is one complex concept that I managed to understand before coming into the JVM space. I say this because…
android.jlelse.eu
반응형