1/* 2 * Copyright 2018 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 17package androidx.fragment.app 18 19/** 20 * Run [body] in a [FragmentTransaction] which is automatically committed if it completes without 21 * exception. 22 * 23 * One of four commit functions will be used based on the values of `now` and `allowStateLoss`: 24 * 25 * | `now` | `allowStateLoss` | Method | 26 * | ----- | ---------------- | ------------------------------ | 27 * | false | false | `commit()` | 28 * | false | true | `commitAllowingStateLoss()` | 29 * | true | false | `commitNow()` | 30 * | true | true | `commitNowAllowingStateLoss()` | 31 */ 32inline fun FragmentManager.transaction( 33 now: Boolean = false, 34 allowStateLoss: Boolean = false, 35 body: FragmentTransaction.() -> Unit 36) { 37 val transaction = beginTransaction() 38 transaction.body() 39 if (now) { 40 if (allowStateLoss) { 41 transaction.commitNowAllowingStateLoss() 42 } else { 43 transaction.commitNow() 44 } 45 } else { 46 if (allowStateLoss) { 47 transaction.commitAllowingStateLoss() 48 } else { 49 transaction.commit() 50 } 51 } 52} 53