koin에서 hilt로 가는 여정

DI가 궁금하시다면 여기 - here

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/e5aae834-f5b4-4239-a1e3-7ab9b89719ae/_2021-07-18__1.58.22.png

HiltAndroidApp

Hilt를 사용하는 모든 앱은 "HiltAndroidApp" 이 달린 Application 클래스를 포함해야 한다.

HiltAndroidApp은 Hilt 컴포넌트의 코드 생성과 컴포넌트를 사용하는 Application의 기본 클래스를 생성하게 된다.

@HiltAndroidApp
class MyApplication : Application() { 
		
		override fun onCreate() {
				super.onCreate() // super.onCreate()에서 의존성을 주입하게 된다.
		}
}

AndroidEntryPoint

Application에서 멤버 주입이 가능하게 설정하고 나면, 다른 안드로이드 클래스들에서도 AndroidEntryPoint anotation을 사용하여 멤버 주입을 하는 것이 가능해 진다. AndroidEntryPoint를 사용할 수 있는 타입은 Activity, Fragment, View, Service, BroadcaseReceiver 이다.

@AndroidEntryPoint
class MyActivity : MyBaseActivity() {
		@Inject lateinit var bar: Bar // ApplicationComponent 또는 ActivityComponent으로 부터 의존성이 주입된다.

		override fun onCreate() {
				super.onCreate() // super.onCreate()에서 의존성 주입이 발생
		// Do something with bar ...
		}
}

Inject

의존성 주입은 2가지로 사용할 수 있다. (생성자 주입, 필드 주입)

// 생성자를 통해 TestService를 주입
class Test @Inject constructor(
		private val service: TestService
) { ... }

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
   @Inject lateinit var adapter: MainAdapter // 필드는 private일 수 없다.
}

HiltViewModel