1 /* 2 * 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 package dagger.hilt.android.internal.managers; 18 19 import static dagger.hilt.internal.Preconditions.checkNotNull; 20 import static dagger.hilt.internal.Preconditions.checkState; 21 22 import android.os.Bundle; 23 import androidx.annotation.Nullable; 24 import androidx.lifecycle.SavedStateHandle; 25 import androidx.lifecycle.SavedStateHandleSupport; 26 import androidx.lifecycle.viewmodel.CreationExtras; 27 import androidx.lifecycle.viewmodel.MutableCreationExtras; 28 import dagger.hilt.android.internal.ThreadUtil; 29 30 /** Implementation for SavedStateHandleHolder. */ 31 public final class SavedStateHandleHolder { 32 private CreationExtras extras; 33 private SavedStateHandle handle; 34 private final boolean nonComponentActivity; 35 SavedStateHandleHolder(@ullable CreationExtras extras)36 SavedStateHandleHolder(@Nullable CreationExtras extras) { 37 nonComponentActivity = (extras == null); 38 this.extras = extras; 39 } 40 getSavedStateHandle()41 SavedStateHandle getSavedStateHandle() { 42 ThreadUtil.ensureMainThread(); 43 checkState( 44 !nonComponentActivity, 45 "Activity that does not extend ComponentActivity cannot use SavedStateHandle"); 46 if (handle != null) { 47 return handle; 48 } 49 checkNotNull( 50 extras, 51 "The first access to SavedStateHandle should happen between super.onCreate() and" 52 + " super.onDestroy()"); 53 // Clean up default args, since those are unused and we don't want to duplicate those for each 54 // SavedStateHandle 55 MutableCreationExtras mutableExtras = new MutableCreationExtras(extras); 56 mutableExtras.set(SavedStateHandleSupport.DEFAULT_ARGS_KEY, Bundle.EMPTY); 57 extras = mutableExtras; 58 handle = SavedStateHandleSupport.createSavedStateHandle(extras); 59 60 extras = null; 61 return handle; 62 } 63 clear()64 public void clear() { 65 extras = null; 66 } 67 setExtras(CreationExtras extras)68 public void setExtras(CreationExtras extras) { 69 if (handle != null) { 70 // If handle is already created, we don't need to store CreationExtras. 71 return; 72 } 73 this.extras = extras; 74 } 75 isInvalid()76 public boolean isInvalid() { 77 return handle == null && extras == null; 78 } 79 } 80