package com.framework.mvvm.mv

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.framework.app.base.IRepository
import kotlin.reflect.KClass

/**
 * ViewModel 工厂
 * 根据 repository 生成 ViewModel
 */
class ViewModelFactory(
    private val repository: IRepository
) : ViewModelProvider.Factory {
    private val map = HashMap<KClass<out IRepository>, ViewModel>()
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        var vm = map[repository::class]
        if (vm == null) {
            val constructor = modelClass.getConstructor(repository.javaClass)
            vm = constructor.newInstance(repository)
            map[repository::class] = vm
        }
        return vm as T
    }
}