查看源码后发现ViewModel是否会复用和两个因素有关,一个是ViewModelStore(用于保存ViewModel实例),另一个是get方法传入的key,如下:
由此我们可以定义一个注解用于标记view model的作用域
package com.cj.customwidget.page.viewmodel
/**
* @package com.cj.customwidget.page.viewmodel
* @author luan
* @date 2020/11/2
* @des 用于标记vm的作用域
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class VMScope(val scopeName:String) {
}
然后通过自定义ViewModelStore来解决view model复用问题
package com.cj.customwidget.page.viewmodel
import androidx.activity.ComponentActivity
import androidx.lifecycle.*
import com.cj.customwidget.p
/**
* @package com.cj.customwidget.page.viewmodel
* @author luan
* @date 2020/11/2
* @des
*/
private val vMStores = HashMap<String, VMStore>()//作用域对应的商店
//反射注入view model
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)) {//如果该作用域存在缓存,则从缓存中获取view model商店
store = vMStores[element]!!
} else {//如果不存在则创建一个新的商店
store = VMStore()
vMStores[element] = store
}
store.bindHost(this)
val clazz = field.type as Class<ViewModel>
val vm = ViewModelProvider(store, VMFactory()).get(clazz)
//给view model赋值
field.set(this, vm)
}
}
}
//自定义商店
class VMStore : ViewModelStoreOwner {
private val bindTargets = ArrayList<LifecycleOwner>()
private var vmStore: ViewModelStore? = null
//绑定
fun bindHost(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) {
bindTargets.remove(host)
if (bindTargets.isEmpty()) {//如果当前商店没有关联对象,则释放内存
vMStores.entries.find { it.value == this@VMStore }?.also {
vmStore?.clear()
vMStores.remove(it.key)
"clear vMStores:${vMStores.size}".p()
}
}
}
}
})
}
}
override fun getViewModelStore(): ViewModelStore {
if (vmStore == null)
vmStore = ViewModelStore()
return vmStore!!
}
}
使用方式:
界面Activity1
package com.cj.customwidget.page.viewmodel
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.cj.customwidget.R
import com.cj.customwidget.p
import kotlinx.android.synthetic.main.activity_v_m1.*
class VM1Activity : AppCompatActivity() {
@VMScope("Lucas")
lateinit var vm:ViewModel1
// val vm by lazy { ViewModelProvider(this).get("lucas",ViewModel1::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectViewModel()
vm.p()
setContentView(R.layout.activity_v_m1)
v_open.setOnClickListener { startActivity(Intent(this,VM2Activity::class.java)) }
}
}
界面Activity2
package com.cj.customwidget.page.viewmodel
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.cj.customwidget.R
import com.cj.customwidget.p
class VM2Activity : AppCompatActivity() {
@VMScope("Lucas")
lateinit var vm:ViewModel1
// val vm by lazy { ViewModelProvider(this).get("lucas",ViewModel1::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectViewModel()
vm.p()
setContentView(R.layout.activity_v_m2)
}
}
界面Fragment
class VMFragment: Fragment() {
@VMScope("Lucas")
lateinit var vm: ViewModel1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectViewModel()
// vm.test()
"page:${this::class.java.simpleName},vm:${vm}".p()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return View.inflate(requireContext(), R.layout.fragment_vm,null)
}
}
查看结果
混淆配置(如果开启混淆,则需加入下列配置,否则会导致注入失败)
-keepclasseswithmembers class * {
@com.cj.customwidget.page.viewmodel.VMScope <fields>;
}
Tip:
该实现方式由于基于反射实现,所以运行开销较大,也不支持创建带参数View Model所以已被弃用,请参考二期优化后的实现方式:
https://www.jianshu.com/p/79d70b2712ee
项目地址:https://github.com/LucasDevelop/CustomView. 中的View model 案例