查看源码后发现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