1package com.bumptech.glide.manager;
2
3import com.bumptech.glide.request.Request;
4
5import java.util.Collections;
6import java.util.Set;
7import java.util.WeakHashMap;
8
9public class RequestTracker {
10    // Most requests will be for views and will therefore be held strongly (and safely) by the view via the tag.
11    // However, a user can always pass in a different type of target which may end up not being strongly referenced even
12    // though the user still would like the request to finish. Weak references are therefore only really functional in
13    // this context for view targets. Despite the side affects, WeakReferences are still essentially required. A user
14    // can always make repeated requests into targets other than views, or use an activity manager in a fragment pager
15    // where holding strong references would steadily leak bitmaps and/or views.
16    private final Set<Request> requests = Collections.newSetFromMap(new WeakHashMap<Request, Boolean>());
17
18    public void addRequest(Request request) {
19        requests.add(request);
20    }
21
22    public void removeRequest(Request request) {
23        requests.remove(request);
24    }
25
26    /**
27     * Stops any in progress requests.
28     */
29    public void pauseRequests() {
30        for (Request request : requests) {
31            if (!request.isComplete() && !request.isFailed()) {
32                request.clear();
33            }
34        }
35    }
36
37    /**
38     * Starts any not yet completed or failed requests.
39     */
40    public void resumeRequests() {
41        for (Request request : requests) {
42            if (!request.isComplete() && !request.isRunning()) {
43                request.run();
44            }
45        }
46    }
47
48    /**
49     * Cancels all requests and clears their resources.
50     */
51    public void clearRequests() {
52        for (Request request : requests) {
53            request.clear();
54        }
55    }
56
57    /**
58     * Restarts failed requests and cancels and restarts in progress requests.
59     */
60    public void restartRequests() {
61        for (Request request : requests) {
62            if (request.isFailed()) {
63                request.run();
64            } else if (!request.isComplete()) {
65                request.clear();
66                request.run();
67            }
68        }
69    }
70}
71