1 /* <lambda>null2 * Copyright 2021 The Android Open Source Project 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 androidx.compose.runtime.saveable 18 19 /** 20 * The [Saver] implementation which allows to represent your class as a map of values which can be 21 * saved individually. 22 * 23 * What types can be saved is defined by [SaveableStateRegistry], by default everything which can be 24 * stored in the Bundle class can be saved. 25 * 26 * You can use it as a parameter for [rememberSaveable]. 27 * 28 * @sample androidx.compose.runtime.saveable.samples.MapSaverSample 29 */ 30 fun <T> mapSaver( 31 save: SaverScope.(value: T) -> Map<String, Any?>, 32 restore: (Map<String, Any?>) -> T? 33 ) = 34 listSaver<T, Any?>( 35 save = { 36 mutableListOf<Any?>().apply { 37 save(it).forEach { entry -> 38 add(entry.key) 39 add(entry.value) 40 } 41 } 42 }, listnull43 restore = { list -> 44 val map = mutableMapOf<String, Any?>() 45 check(list.size.rem(2) == 0) { "non-zero remainder" } 46 var index = 0 47 while (index < list.size) { 48 val key = list[index] as String 49 val value = list[index + 1] 50 map[key] = value 51 index += 2 52 } 53 restore(map) 54 } 55 ) 56