Last active
May 16, 2018 08:13
-
-
Save arekolek/e5083776d263b16666aff38dd0d3c439 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import android.arch.lifecycle.ViewModel | |
import android.arch.lifecycle.ViewModelProvider | |
import javax.inject.Inject | |
import javax.inject.Provider | |
/** | |
* Lets us use [Inject] annotations on [ViewModel] classes. | |
* | |
* To use it, include the [ViewModelModule] in the module that binds the ViewModel itself. | |
*/ | |
class ViewModelFactory @Inject constructor( | |
private val providers: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>> | |
) : ViewModelProvider.Factory { | |
override fun <T : ViewModel> create(modelClass: Class<T>): T { | |
// check if modelClass is provided or is a superclass of provided one | |
val provider = providers[modelClass] | |
?: providers.entries.find { modelClass.isAssignableFrom(it.key) }?.value | |
?: throw IllegalArgumentException("Unknown model class $modelClass") | |
try { | |
@Suppress("UNCHECKED_CAST") | |
return provider.get() as T | |
} catch (e: Exception) { | |
throw RuntimeException("There was an error providing an instance of $modelClass", e) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import android.arch.lifecycle.ViewModel | |
import dagger.MapKey | |
import kotlin.reflect.KClass | |
@MapKey | |
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) | |
annotation class ViewModelKey(val value: KClass<out ViewModel>) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import android.arch.lifecycle.ViewModelProvider | |
import dagger.Binds | |
import dagger.Module | |
@Module | |
interface ViewModelModule { | |
@Binds | |
fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment