Skip to content

Instantly share code, notes, and snippets.

@juliendn
Last active February 22, 2018 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliendn/f35f2646c70481ad1de2cb35652e0600 to your computer and use it in GitHub Desktop.
Save juliendn/f35f2646c70481ad1de2cb35652e0600 to your computer and use it in GitHub Desktop.
VM kotlin integration
class ChronoActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// The ViewModelStore provides a new ViewModel or one previously created.
val chronometerViewModel = getViewModel(this) {
ChronometerViewModel(SystemClock.elapsedRealtime())
}
// Get the chronometer reference
val chronometer = findViewById<Chronometer>(R.id.chronometer)
chronometer.base = chronometerViewModel.startTime
chronometer.start()
}
}
class ChronometerViewModel(val startTime: Long) : ViewModel()
class ViewModelFactory<VM : ViewModel>(private val creation: () -> VM) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T = creation() as T
}
inline fun <reified VM : ViewModel> getViewModel(activity: FragmentActivity, key: String? = null, noinline creation: () -> VM): VM {
return ViewModelProviders
.of(activity, ViewModelFactory(creation))
.run {
if (null == key) {
get(VM::class.java)
} else {
get(key, VM::class.java)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment