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.annotation.NonNull; 19 import androidx.lifecycle.Lifecycle; 20 import androidx.lifecycle.Lifecycle.Event; 21 import androidx.lifecycle.LifecycleEventObserver; 22 import androidx.lifecycle.LifecycleOwner; 23 24 public interface CallbackController<T> { 25 26 /** Add a callback */ addCallback(@onNull T listener)27 void addCallback(@NonNull T listener); 28 29 /** Remove a callback */ removeCallback(@onNull T listener)30 void removeCallback(@NonNull T listener); 31 32 /** 33 * Wrapper to {@link #addCallback(Object)} when a lifecycle is in the resumed state 34 * and {@link #removeCallback(Object)} when not resumed automatically. 35 */ observe(LifecycleOwner owner, T listener)36 default T observe(LifecycleOwner owner, T listener) { 37 return observe(owner.getLifecycle(), listener); 38 } 39 40 /** 41 * Wrapper to {@link #addCallback(Object)} when a lifecycle is in the resumed state 42 * and {@link #removeCallback(Object)} when not resumed automatically. 43 */ observe(Lifecycle lifecycle, T listener)44 default T observe(Lifecycle lifecycle, T listener) { 45 lifecycle.addObserver((LifecycleEventObserver) (lifecycleOwner, event) -> { 46 if (event == Event.ON_RESUME) { 47 addCallback(listener); 48 } else if (event == Event.ON_PAUSE) { 49 removeCallback(listener); 50 } 51 }); 52 return listener; 53 } 54 } 55