Search code examples
androiddagger-hilt

Will I get the same instance of ViewModel() when I use Hilt as DI in Android Studio project?


I use Hilt as as DI in Android Studio project, I know there are two ways to create the instance of ViewModel().

Way 1

way1: RecordSoundViewModel = hiltViewModel()

Way 2

val way2: RecordSoundViewModel by viewModels()

1: Coudl you tell me if viewModel1, viewModel2, viewModel3 and viewModel4 is the same instance of RecordSoundViewModel?

2: If the four instances are not the same instance of RecordSoundViewModel, how can I get the same instance?

@AndroidEntryPoint
class ActivityMain : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)     
        val viewModel3: RecordSoundViewModel by viewModels()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val viewModel4: RecordSoundViewModel by viewModels()
    }
}

@Composable
fun ScreenHome_Line(    
    viewModel1: RecordSoundViewModel = hiltViewModel()
) {

}

@Composable
fun ScreenHome_Recording(   
    viewModel2: RecordSoundViewModel = hiltViewModel()
) {

}



@HiltViewModel
class RecordSoundViewModel @Inject constructor(
    ...
): ViewModel()
{
   ...
}

Solution

  • Yes you can use the same viewmodel instance.

    It is understood when the source code is examined.

    public class ViewModelLazy<VM : ViewModel> @JvmOverloads constructor(
        private val viewModelClass: KClass<VM>,
        private val storeProducer: () -> ViewModelStore,
        private val factoryProducer: () -> ViewModelProvider.Factory,
        private val extrasProducer: () -> CreationExtras = { CreationExtras.Empty }
    ) : Lazy<VM> {
        private var cached: VM? = null
    
        override val value: VM
            get() {
                val viewModel = cached
                return if (viewModel == null) {
                    val factory = factoryProducer()
                    val store = storeProducer()
                    ViewModelProvider(
                        store,
                        factory,
                        extrasProducer()
                    ).get(viewModelClass.java).also {
                        cached = it
                    }
                } else {
                    viewModel
                }
            }
    
        override fun isInitialized(): Boolean = cached != null
    }