[TIL] ๐ŸŒผ24/04/27๐ŸŒผ#Hilt @Binds @Provides

0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
89/104
post-thumbnail
post-custom-banner

[TIL] ๐ŸŒผ24/04/27๐ŸŒผ#Hilt @Binds @Provides

Hilt @Binds @Provides

๐Ÿ“Œ์ฐธ๊ณ ์ž๋ฃŒ

  • Hilt๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ํ”„๋กœ์ ํŠธ ๋‚ด์—์„œ constructor๋ฅผ ํ†ตํ•ด ํด๋ž˜์Šค์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ, ๋ฐ”๋กœ ์ข…์†์„ฑ์„ ์ œ๊ณตํ•  ์ˆ˜ ์žˆ์Œ (= constructor-injection)
    -> ๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ, Hilt Module์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์ข…์†์„ฑ์„ ์ œ๊ณตํ•ด์•ผ
  • Hilt Module์„ ํ†ตํ•ด ์ œ๊ณตํ•ด์•ผ ํ•˜๋Š” ์ข…์†์„ฑ์˜ ์ข…๋ฅ˜์— ๋”ฐ๋ผ @Binds ๋˜๋Š” @Provides ์‚ฌ์šฉ
  • @Binds
    • ์ธํ„ฐํŽ˜์ด์Šค์— ๋Œ€ํ•œ ์ข…์†์„ฑ ์‚ฝ์ž…์— ์‚ฌ์šฉ
    • abstract class ๋ชจ๋“ˆ ์•ˆ์— abstract function ์ •์˜
      • ํ•จ์ˆ˜ return ํƒ€์ž…: ์ œ๊ณตํ•˜๋Š” ์ธ์Šคํ„ด์Šค์˜ ์ธํ„ฐํŽ˜์ด์Šค
      • ํ•จ์ˆ˜ parameter: Hilt๊ฐ€ ์ œ๊ณตํ•  ์ธํ„ฐํŽ˜์ด์Šค์˜ ๊ตฌํ˜„ ๊ฐ์ฒด
@Module
@InstallIn(ViewModelComponent::class)
abstract class RepositoryModule {
    @Binds
    abstract fun bindsItemRepository(repositoryImpl: ItemRepositoryImpl): ItemRepository
}
  • @Provides
    • ์™ธ๋ถ€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์—์„œ ์ œ๊ณต๋˜๋Š” ํด๋ž˜์Šค์ด๋ฏ€๋กœ ํ”„๋กœ์ ํŠธ ๋‚ด์—์„œ ์†Œ์œ ํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ/Builder ํŒจํ„ด์„ ํ†ตํ•ด ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ ์‚ฌ์šฉ
    • object ๋ชจ๋“ˆ ์•ˆ์— function ์ •์˜
      • ํ•จ์ˆ˜ return ํƒ€์ž…: ์ œ๊ณตํ•˜๋Š” ์ธ์Šคํ„ด์Šค์˜ ํƒ€์ž…
      • ํ•จ์ˆ˜ parameters: ํ•ด๋‹น ํƒ€์ž…์˜ ์ข…์†์„ฑ
      • ํ•จ์ˆ˜ body: ์ œ๊ณตํ•˜๋Š” ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ๋ฐฉ๋ฒ•, Hilt๊ฐ€ ํ•ด๋‹น ํƒ€์ž…์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ์ œ๊ณตํ•ด์•ผํ•  ๋•Œ๋งˆ๋‹ค ์‹คํ–‰๋จ
@Module
@InstallIn(SingletonComponent::class)
object RemoteSourceModule {
    @Singleton
    @Provides
    fun provideKakaoSearchApi() = KakaoSearchRetrofit.kakaoSearchApi
}
  • @Provides๋งŒ ํฌํ•จ๋˜๋Š” Module์˜ ๊ฒฝ์šฐ object๋กœ ์ƒ์„ฑ
    -> providers get optimized & almost in-lined in generated code
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€