1 /* <lambda>null2 * Copyright (C) 2023 The Dagger Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 @file:JvmName("HiltViewModelExtensions") 18 19 package dagger.hilt.android.lifecycle 20 21 import androidx.lifecycle.ViewModel 22 import androidx.lifecycle.viewmodel.CreationExtras 23 import androidx.lifecycle.viewmodel.MutableCreationExtras 24 import dagger.hilt.android.internal.lifecycle.HiltViewModelFactory 25 26 /** 27 * Returns a new {@code CreationExtras} with the original entries plus the passed in creation 28 * callback. The callback is used by Hilt to create {@link AssistedInject}-annotated {@link 29 * HiltViewModel}s. 30 * 31 * @param callback A creation callback that takes an assisted factory and returns a {@code 32 * ViewModel}. 33 */ 34 fun <VMF> CreationExtras.withCreationCallback(callback: (VMF) -> ViewModel): CreationExtras = 35 MutableCreationExtras(this).addCreationCallback(callback) 36 37 /** 38 * Returns the {@code MutableCreationExtras} with the passed in creation callback added. The 39 * callback is used by Hilt to create {@link AssistedInject}-annotated {@link HiltViewModel}s. 40 * 41 * @param callback A creation callback that takes an assisted factory and returns a {@code 42 * ViewModel}. 43 */ 44 @Suppress("UNCHECKED_CAST") 45 fun <VMF> MutableCreationExtras.addCreationCallback(callback: (VMF) -> ViewModel): CreationExtras = 46 this.apply { 47 this[HiltViewModelFactory.CREATION_CALLBACK_KEY] = { factory -> callback(factory as VMF) } 48 } 49