Android 多个Activity之间共享一个ViewModel对象,并扩展作用域注解

查看源码后发现ViewModel是否会复用和两个因素有关,一个是ViewModelStore(用于保存ViewModel实例),另一个是get方法传入的key,如下:


image.png

由此我们可以定义一个注解用于标记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 ComponentActivity.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!!
    }
}

class VMFactory : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return modelClass.newInstance()
    }

}

使用方式:
界面1

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)) }
    }
}

界面2

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)
    }
}

查看结果


image.png

项目地址:https://github.com/LucasDevelop/CustomView. 中的View model 案例