1/*
2 * Copyright (C) 2013 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
17package com.android.documentsui;
18
19import android.content.AsyncTaskLoader;
20import android.content.Context;
21
22import com.android.documentsui.model.RootInfo;
23
24import java.util.Collection;
25
26public class RootsLoader extends AsyncTaskLoader<Collection<RootInfo>> {
27    private final ForceLoadContentObserver mObserver = new ForceLoadContentObserver();
28
29    private final RootsCache mRoots;
30    private final State mState;
31
32    private Collection<RootInfo> mResult;
33
34    public RootsLoader(Context context, RootsCache roots, State state) {
35        super(context);
36        mRoots = roots;
37        mState = state;
38
39        getContext().getContentResolver()
40                .registerContentObserver(RootsCache.sNotificationUri, false, mObserver);
41    }
42
43    @Override
44    public final Collection<RootInfo> loadInBackground() {
45        return mRoots.getMatchingRootsBlocking(mState);
46    }
47
48    @Override
49    public void deliverResult(Collection<RootInfo> result) {
50        if (isReset()) {
51            return;
52        }
53
54        mResult = result;
55
56        if (isStarted()) {
57            super.deliverResult(result);
58        }
59    }
60
61    @Override
62    protected void onStartLoading() {
63        if (mResult != null) {
64            deliverResult(mResult);
65        }
66        if (takeContentChanged() || mResult == null) {
67            forceLoad();
68        }
69    }
70
71    @Override
72    protected void onStopLoading() {
73        cancelLoad();
74    }
75
76    @Override
77    protected void onReset() {
78        super.onReset();
79
80        // Ensure the loader is stopped
81        onStopLoading();
82
83        mResult = null;
84
85        getContext().getContentResolver().unregisterContentObserver(mObserver);
86    }
87}
88