1package com.bumptech.glide.manager;
2
3import java.util.Collections;
4import java.util.Set;
5import java.util.WeakHashMap;
6
7/**
8 * A {@link com.bumptech.glide.manager.Lifecycle} implementation for tracking and notifying listeners of
9 * {@link android.app.Fragment} and {@link android.app.Activity} lifecycle events.
10 */
11class ActivityFragmentLifecycle implements Lifecycle {
12    private final Set<LifecycleListener> lifecycleListeners =
13            Collections.synchronizedSet(Collections.newSetFromMap(new WeakHashMap<LifecycleListener, Boolean>()));
14    private boolean isStarted;
15    private boolean isDestroyed;
16
17    /**
18     * Adds the given listener to the list of listeners to be notified on each lifecycle event.
19     *
20     * <p>
21     *     The latest lifecycle event will be called on the given listener synchronously in this method. If the
22     *     activity or fragment is stopped, {@link LifecycleListener#onStop()}} will be called, and same for onStart and
23     *     onDestroy.
24     * </p>
25     *
26     * <p>
27     *     Note - {@link com.bumptech.glide.manager.LifecycleListener}s that are added more than once will have their
28     *     lifecycle methods called more than once. It is the caller's responsibility to avoid adding listeners
29     *     multiple times.
30     * </p>
31     */
32    @Override
33    public void addListener(LifecycleListener listener) {
34        lifecycleListeners.add(listener);
35
36        if (isDestroyed) {
37            listener.onDestroy();
38        } else if (isStarted) {
39            listener.onStart();
40        } else {
41            listener.onStop();
42        }
43    }
44
45    void onStart() {
46        isStarted = true;
47        for (LifecycleListener lifecycleListener : lifecycleListeners) {
48            lifecycleListener.onStart();
49        }
50    }
51
52    void onStop() {
53        isStarted = false;
54        for (LifecycleListener lifecycleListener : lifecycleListeners) {
55            lifecycleListener.onStop();
56        }
57    }
58
59    void onDestroy() {
60        isDestroyed = true;
61        for (LifecycleListener lifecycleListener : lifecycleListeners) {
62            lifecycleListener.onDestroy();
63        }
64    }
65}
66