sumanth grandhae
sumanth grandhae

Reputation: 13

is there any way to use AsyncTask without memory leak in android using java

I would like to know is there any way to use async task without leaking any memory. Tried using interfaces, passing via constructor making async task as static etc.,all there will result in leaking context.

Upvotes: 1

Views: 264

Answers (2)

Geo
Geo

Reputation: 756

Use WeakRefrence of Context.

   static class MyAsyncTask extends AsyncTask<Void,Void,Void>{
    private WeakReference<Context> contextWeakReference;
    public MyAsyncTask(Context context){
        this.contextWeakReference=new WeakReference<>(context);
    }
    @Override
    protected Void doInBackground(Void... voids) {
        Context context=contextWeakReference.get();
        if (context!=null){
            //Do your stuff
        }
        return null;
    }
  }

Read more about WeakRefrence

Upvotes: 2

Royi
Royi

Reputation: 306

I would recommended to use Executor to execute the relevant code asynchronously e.g:

public static final Executor oneThreadExecutor = Executors.newSingleThreadExecutor();
public static final Executor threadPoolExecutor = Executors.newFixedThreadPool(nThreads);

public LiveData<Object> getStuffData(Executor executor){
    final MutableLiveData<Object> stuffData = new MutableLiveData<>();

    executor.execute(new Runnable() {
        @Override
        public void run() {
            // Should replace AsyncTask.doInBackground
            // do your async stuff here and post it to 'stuffData'
            stuffData.postValue(new Object());
        }
    });

    return stuffData;
}

// should called from LifeCycleOwner
public void observeStuffData(){
    getStuffData(threadPoolExecutor).observe(/*Activity/ Fragment view life cycle owner*/, new Observer<Object>() {
        @Override
        public void onChanged(Object o) {
            // Should replace AsyncTask.onPostExecute
        }
    });
}

Upvotes: 1

Related Questions