Home | History | Annotate | Download | only in base
      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
     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 
     17 package com.android.documentsui.base;
     18 
     19 import android.os.AsyncTask;
     20 
     21 /**
     22  * An {@link AsyncTask} that guards work with checks that a paired {@link Check}
     23  * has not yet given signals to stop progress.
     24  *
     25  * <p>Use this type of task for greater safety when executing tasks that might complete
     26  * after the owner of the task has explicitly given a signal to stop progress.
     27  *
     28  * <p>Also useful as tasks can be static, limiting scope, but still have access to
     29  * signal from the owning class.
     30  *
     31  * @template Input input type
     32  * @template Output output type
     33  */
     34 public abstract class CheckedTask<Input, Output>
     35         extends AsyncTask<Input, Void, Output> {
     36 
     37     private Check mCheck;
     38 
     39     public CheckedTask(Check check) {
     40         mCheck = check;
     41     }
     42 
     43     /** Called prior to run being executed. Analogous to {@link AsyncTask#onPreExecute} */
     44     protected void prepare() {}
     45 
     46     /** Analogous to {@link AsyncTask#doInBackground} */
     47     protected abstract Output run(Input... input);
     48 
     49     /** Analogous to {@link AsyncTask#onPostExecute} */
     50     protected abstract void finish(Output output);
     51 
     52     @Override
     53     protected final void onPreExecute() {
     54         if (mCheck.stop()) {
     55             return;
     56         }
     57         prepare();
     58     }
     59 
     60     @Override
     61     protected final Output doInBackground(Input... input) {
     62         if (mCheck.stop()) {
     63             return null;
     64         }
     65         return run(input);
     66     }
     67 
     68     @Override
     69     protected final void onPostExecute(Output result) {
     70         if (mCheck.stop()) {
     71             return;
     72         }
     73         finish(result);
     74     }
     75 
     76     @FunctionalInterface
     77     public interface Check {
     78         boolean stop();
     79     }
     80 }
     81