查看源碼后發(fā)現(xiàn)ViewModel是否會(huì)復(fù)用和兩個(gè)因素有關(guān),一個(gè)是ViewModelStore(用于保存ViewModel實(shí)例)沦童,另一個(gè)是get方法傳入的key仑濒,如下:
由此我們可以定義一個(gè)注解用于標(biāo)記view model的作用域
package com.cj.customwidget.page.viewmodel
/**
* @package com.cj.customwidget.page.viewmodel
* @author luan
* @date 2020/11/2
* @des 用于標(biāo)記vm的作用域
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class VMScope(val scopeName:String) {
}
然后通過自定義ViewModelStore來解決view model復(fù)用問題
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>()//作用域?qū)?yīng)的商店
//反射注入view model
fun LifecycleOwner.injectViewModel() {
//根據(jù)作用域創(chuàng)建商店
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 {//如果不存在則創(chuàng)建一個(gè)新的商店
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()) {//如果當(dāng)前商店沒有關(guān)聯(lián)對(duì)象偷遗,則釋放內(nèi)存
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)
}
}
查看結(jié)果
混淆配置(如果開啟混淆墩瞳,則需加入下列配置,否則會(huì)導(dǎo)致注入失敗)
-keepclasseswithmembers class * {
@com.cj.customwidget.page.viewmodel.VMScope <fields>;
}
Tip:
該實(shí)現(xiàn)方式由于基于反射實(shí)現(xiàn)氏豌,所以運(yùn)行開銷較大喉酌,也不支持創(chuàng)建帶參數(shù)View Model所以已被棄用,請(qǐng)參考二期優(yōu)化后的實(shí)現(xiàn)方式:
http://www.reibang.com/p/79d70b2712ee
項(xiàng)目地址:https://github.com/LucasDevelop/CustomView. 中的View model 案例