• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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.keyguard;
18 
19 import androidx.annotation.NonNull;
20 
21 import com.android.app.tracing.TraceUtils;
22 
23 import kotlin.Unit;
24 
25 import java.util.ArrayList;
26 import java.util.Objects;
27 import java.util.function.BiConsumer;
28 import java.util.function.Consumer;
29 
30 /**
31  * Base class for lifecycles with observers.
32  */
33 public class Lifecycle<T> {
34 
35     private final ArrayList<T> mObservers = new ArrayList<>();
36 
addObserver(@onNull T observer)37     public void addObserver(@NonNull T observer) {
38         mObservers.add(Objects.requireNonNull(observer));
39     }
40 
removeObserver(T observer)41     public void removeObserver(T observer) {
42         mObservers.remove(observer);
43     }
44 
dispatch(Consumer<T> consumer)45     public void dispatch(Consumer<T> consumer) {
46         for (int i = 0; i < mObservers.size(); i++) {
47             final T observer = mObservers.get(i);
48             TraceUtils.trace(() -> "dispatch#" + consumer.toString(), () -> {
49                 consumer.accept(observer);
50                 return Unit.INSTANCE;
51             });
52         }
53     }
54 
55     /**
56      * Will dispatch the consumer to the observer, along with a single argument of type<U>.
57      */
dispatch(BiConsumer<T, U> biConsumer, U arg)58     public <U> void dispatch(BiConsumer<T, U> biConsumer, U arg) {
59         for (int i = 0; i < mObservers.size(); i++) {
60             final T observer = mObservers.get(i);
61             TraceUtils.trace(() -> "dispatch#" + biConsumer.toString(), () -> {
62                 biConsumer.accept(observer, arg);
63                 return Unit.INSTANCE;
64             });
65         }
66     }
67 }
68