1 /*
2  * Copyright (C) 2016 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 distributed under the
11  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
12  * KIND, either express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */
15 
16 package com.android.systemui.statusbar.policy;
17 
18 import androidx.lifecycle.Lifecycle;
19 import androidx.lifecycle.Lifecycle.Event;
20 import androidx.lifecycle.LifecycleEventObserver;
21 import androidx.lifecycle.LifecycleOwner;
22 
23 public interface CallbackController<T> {
addCallback(T listener)24     void addCallback(T listener);
removeCallback(T listener)25     void removeCallback(T listener);
26 
27     /**
28      * Wrapper to {@link #addCallback(Object)} when a lifecycle is in the resumed state
29      * and {@link #removeCallback(Object)} when not resumed automatically.
30      */
observe(LifecycleOwner owner, T listener)31     default T observe(LifecycleOwner owner, T listener) {
32         return observe(owner.getLifecycle(), listener);
33     }
34 
35     /**
36      * Wrapper to {@link #addCallback(Object)} when a lifecycle is in the resumed state
37      * and {@link #removeCallback(Object)} when not resumed automatically.
38      */
observe(Lifecycle lifecycle, T listener)39     default T observe(Lifecycle lifecycle, T listener) {
40         lifecycle.addObserver((LifecycleEventObserver) (lifecycleOwner, event) -> {
41             if (event == Event.ON_RESUME) {
42                 addCallback(listener);
43             } else if (event == Event.ON_PAUSE) {
44                 removeCallback(listener);
45             }
46         });
47         return listener;
48     }
49 }
50