Last active
June 9, 2018 13:17
-
-
Save panpf/34aa0d5d7874474a0afab5c210f76b6b to your computer and use it in GitHub Desktop.
Android arch ViewModel kotlin bind
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
@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