Skip to content

Spotify Clone App: Lesson 8

Mert Şimşek edited this page Oct 29, 2019 · 4 revisions

Overview

In this lesson, we will learn

  • Inject into Retrofit, OkHttp using Dagger 2
  • Inject into ViewModel using Dagger 2
  • Applying Dependency Injection everywhere in our app

We will learn

  • Using Injection in Fragments/Activities.
  • Constructor injection.
  • Inject into ViewModels with ViewModelProvider.Factory.

Prepared Sources

We need these codes in our project. You can create by yourself those codes but I added to here for simplicity.

class ViewModelFactory @Inject constructor(private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) :
    ViewModelProvider.Factory {

    override fun <T : ViewModel> create(modelClass: Class<T>): T =
        viewModels[modelClass]?.get() as T
}
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@MapKey
internal annotation class ViewModelKey(val value: KClass<out ViewModel>)
@Module
abstract class ViewModelModule {

    @Binds
    internal abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
}

Source Code

Branch Lesson 8

Lesson Video

  • Will be available on youtube soon.

Clone this wiki locally