1 /*
2  * Copyright (C) 2024 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 com.android.systemui.util.kotlin
18 
19 import kotlinx.coroutines.DisposableHandle
20 
21 /** A mutable collection of [DisposableHandle] objects that is itself a [DisposableHandle] */
22 class DisposableHandles : DisposableHandle {
23     private val handles = mutableListOf<DisposableHandle>()
24 
25     /** Add the provided handles to this collection. */
addnull26     fun add(vararg handles: DisposableHandle) {
27         this.handles.addAll(handles)
28     }
29 
30     /** Same as [add] */
plusAssignnull31     operator fun plusAssign(handle: DisposableHandle) {
32         this.handles.add(handle)
33     }
34 
35     /** Same as [add] */
plusAssignnull36     operator fun plusAssign(handles: Iterable<DisposableHandle>) {
37         this.handles.addAll(handles)
38     }
39 
40     /** [dispose] the current contents, then [add] the provided [handles] */
replaceAllnull41     fun replaceAll(vararg handles: DisposableHandle) {
42         dispose()
43         add(*handles)
44     }
45 
46     /** Dispose of all added handles and empty this collection. */
disposenull47     override fun dispose() {
48         handles.forEach { it.dispose() }
49         handles.clear()
50     }
51 }
52