Created
          August 23, 2013 10:24 
        
      - 
      
- 
        Save akhy/6317789 to your computer and use it in GitHub Desktop. 
    Wrapper abstract class for Android's built-in AsyncTask with weak reference to target object. For example you can do any image processing in background (asynchronously) and set the output to a garbage collectible ImageView once completed. If for some reason the ImageView isn't available anymore (e.g. due to user switching activity), the `applyOu…
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package net.akhyar.android.async; | |
| import java.lang.ref.WeakReference; | |
| import android.os.AsyncTask; | |
| public abstract class WeakTask<I, O, T> extends AsyncTask<Void, Void, O> { | |
| protected final WeakReference<T> targetRef; | |
| protected I input; | |
| public WeakTask(I input, T target) { | |
| this.input = input; | |
| targetRef = new WeakReference<T>(target); | |
| } | |
| @Override | |
| protected O doInBackground(Void... args) { | |
| return process(input); | |
| } | |
| protected abstract O process(I input); | |
| @Override | |
| protected void onPostExecute(O output) { | |
| final T target = targetRef.get(); | |
| if (target != null) | |
| applyOutputToTarget(output, target); | |
| } | |
| protected abstract void applyOutputToTarget(O output, T target); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Sample usage: