Skip to content

Instantly share code, notes, and snippets.

@hantrungkien
Last active September 17, 2020 16:12
Show Gist options
  • Save hantrungkien/acbf28876a8777c50c0810f522a279d6 to your computer and use it in GitHub Desktop.
Save hantrungkien/acbf28876a8777c50c0810f522a279d6 to your computer and use it in GitHub Desktop.
Hilt
@HiltAndroidApp
class MyApplication : Application() {
@Inject
@UserModelSingletonQualifier
lateinit var singletonUserModel: UserModel
override fun onCreate() {
super.onCreate()
singletonUserModel.value += "MyApplication"
}
}
@AndroidEntryPoint
class SplashActivity : AppCompatActivity() {
private val splashViewModel by viewModels<SplashViewModel>()
private lateinit var binding: SplashActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = SplashActivityBinding.inflate(LayoutInflater.from(this))
setContentView(binding.root)
Timber.e("singleton userModel = ${splashViewModel.singletonUserModel}")
splashViewModel.get("demo_key")
.observe(this, Observer {
Timber.e("demo_key = $it")
})
splashViewModel.put("demo_key", "demo_value")
binding.buttonFeature.setOnClickListener {
val clazz = Class.forName("com.kienht.dagger.hilt.feature.FeatureActivity")
startActivity(Intent(this, clazz))
}
}
}
class SplashViewModel @ViewModelInject constructor(
@UserModelSingletonQualifier val singletonUserModel: UserModel,
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
fun get(key: String) = savedStateHandle.getLiveData<String>(key)
fun put(key: String, value: String) = savedStateHandle.set(key, value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment