Skip to content

Instantly share code, notes, and snippets.

@panpf
Last active June 9, 2018 13:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panpf/34aa0d5d7874474a0afab5c210f76b6b to your computer and use it in GitHub Desktop.
Save panpf/34aa0d5d7874474a0afab5c210f76b6b to your computer and use it in GitHub Desktop.
Android arch ViewModel kotlin bind
@file:Suppress("RedundantVisibilityModifier")
package me.panpf.arch.ktx
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProviders
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
@Suppress("unused")
public fun <V : ViewModel> Fragment.bindViewModel(clazz: KClass<V>): ReadOnlyProperty<Fragment, V> {
return ViewModelLazy { ref, _: KProperty<*> -> ViewModelProviders.of(ref).get(clazz.java) }
}
@Suppress("unused")
public fun <V : ViewModel> FragmentActivity.bindViewModel(clazz: KClass<V>): ReadOnlyProperty<FragmentActivity, V> {
return ViewModelLazy { ref, _: KProperty<*> -> ViewModelProviders.of(ref).get(clazz.java) }
}
private class ViewModelLazy<in REF, out OUT>(val initializer: (REF, KProperty<*>) -> OUT) : ReadOnlyProperty<REF, OUT> {
private object EMPTY
var viewModel: Any? = EMPTY
override fun getValue(thisRef: REF, property: KProperty<*>): OUT {
if (viewModel == EMPTY) {
viewModel = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return viewModel as OUT
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment