buildscript {
...
dependencies {
...
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'
}
}
...
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation "com.google.dagger:hilt-android:2.28-alpha"
kapt "com.google.dagger:hilt-android-compiler:2.28-alpha"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01"
kapt "androidx.hilt:hilt-compiler:1.0.0-alpha01"
}
@HiltAndroidApp
class App : Application() {
override fun onCreate() {
super.onCreate()
// startKoin{
// androidContext(this@App)
// modules(appModule)
// }
}
}
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
...
}
이런 느낌?
아래는 Koin 소스
val appModule = module {
single { AppDatabase.getInstance(androidContext()).itemDao() }
single {
Retrofit.Builder()
.baseUrl(Define.URL_HOST)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.apply {
client(apiInterceptor)
}
.build().create(ItemService::class.java)
}
viewModel { MainViewModel() }
viewModel { RoomPagedListViewModel(get()) }
viewModel {
NetworkPagedListViewModel(
get()
)
}
}
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Singleton
@Provides
fun provideItemDao(@ApplicationContext context: Context): ItemDao {
return AppDatabase.getInstance(context).itemDao()
}
@Singleton
@Provides
fun provideItemService(@ApplicationContext context: Context): ItemService {
return Retrofit.Builder()
.baseUrl(Define.URL_HOST)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.apply {
client(apiInterceptor)
}
.build().create(ItemService::class.java)
}
}
@AndroidEntryPoint
class RoomPagedListFragment : BaseFragment<FragmentListPagedRoomBinding>() {
//기존 koin ext
//private val viewModel by viewModel<RoomPagedListViewModel>()
//androidx.fragment.app.viewModels 이용
private val viewModel by viewModels<RoomPagedListViewModel>()
...
}
class RoomPagedListViewModel @ViewModelInject constructor(private val itemDao: ItemDao) :
ViewModel() {
...
}
변경된 전체 소스는 Github AndroidSample 에.
생각보다 몇 줄 안되는 코드로 koin 에서 hilt 로 변경이 되었다.
아직 alpha 인 만큼 api 의 변경이 많이 있을 수 있으니.. 변경되는 사항들을 지켜보자.