参考资料 https://www.jianshu.com/p/f211ca175a25
工程目录如下:
首先定义一个注解,确定ViewModel的store作用域,内容如下
/**
* 用于标记viewmodel的作用域
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class VMScope(val scopeName:String) {
}
自定义一个 ViewModelStoreOwner,来处理 ViewModel复用问题
private val vMStores = HashMap<String, VMStore>()
fun LifecycleOwner.injectViewModel() {
//根据作用域创建商店
this::class.java.declaredFields.forEach { field ->
field.getAnnotation(VMScope::class.java)?.also { scope ->
val element = scope.scopeName
var store: VMStore
if (vMStores.keys.contains(element)) {
store = vMStores[element]!!
} else {
store = VMStore()
vMStores[element] = store
}
store.register(this)
val clazz = field.type as Class<ViewModel>
val vm = ViewModelProvider(store, ViewModelProvider.NewInstanceFactory()).get(clazz)
field.set(this, vm)
}
}
}
class VMStore : ViewModelStoreOwner {
private val bindTargets = ArrayList<LifecycleOwner>()
private var vmStore: ViewModelStore? = null
fun register(host: LifecycleOwner) {
if (!bindTargets.contains(host)) {
bindTargets.add(host)
host.lifecycle.addObserver(object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (event == Lifecycle.Event.ON_DESTROY) {
host.lifecycle.removeObserver(this)
bindTargets.remove(host)
if (bindTargets.isEmpty()) {//如果当前商店没有关联对象,则释放资源
vMStores.entries.find { it.value == this@VMStore }?.also {
vmStore?.clear()
vMStores.remove(it.key)
}
}
}
}
})
}
}
override fun getViewModelStore(): ViewModelStore {
if (vmStore == null)
vmStore = ViewModelStore()
return vmStore!!
}
}
我们定义一个ViewModel来实现计数器
class CountViewModel : ViewModel() {
val count: MutableLiveData<Int> by lazy { MutableLiveData() }
fun setCount(value: Int?) {
count.value = value
}
}
最后就是在activity里面使用。
class MainActivity : AppCompatActivity() {
@VMScope("count")
lateinit var viewModel:CountViewModel
@RequiresApi(Build.VERSION_CODES.P)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectViewModel()
setContentView(R.layout.activity_main)
}
}
CSDN下载地址 (免费下载) 使用ViewModel解决多个Activity数据共享问题(Kotlin版)-Android文档类资源-CSDN下载