0

I am trying to chain a few AsyncTask classes inside a single Activity, which will then show another Activity once they are all completed (successfully). Currently I am chaining them off each others' onPostExecute() method but I do not like this because it somewhat couples the implementations unnecessarily.

For example, I have my ImportVideoActivity which the users enters a YouTube URL to be downloaded. To do so, I have two AsyncTask classes:

  • YouTubeVideoInfoTask : Gets the video metadata info as well as enumerating through available video formats (quality and codecs).
  • YouTubeVideoDownloadTask : Performs the video download given a URL from the video info metadata.

I want the ImportVideoActivity to first execute a YouTubeVideoInfoTask to enumerate the video qualities and pick the best one. After that, it should execute a YouTubeVideoDownloadTask and upon completion start the CropVideoActivity with the downloaded video.

How can I chain these two AsyncTask classes elegantly inside of the ImportVideoActivity? Is there some kind of listener/callback that allows me to monitor when these tasks complete and start the next one without using the AsyncTask.onPostExecute() method?

Erik
  • 12,730
  • 5
  • 36
  • 42
  • As the second task is dependent on the outcome of the first task why don't you just perform the two in a single `AsyncTask`? – Squonk Jun 12 '14 at 22:22
  • While you are correct that the URL for the second test is part of the return of the first task, they can be done independently. For example, in another portion of the code I may want to simply fetch video details like title, duration, author, etc... without downloading. Just the 'Clean Code' side of me dislikes needless coupling. – Erik Jun 12 '14 at 22:26
  • In that case I'd probably put the code for each part into methods of a POJO helper for reusability. – Squonk Jun 12 '14 at 22:34
  • Some of them are, the `AsyncTask` portion is really just `HTTLURLConnection` that gets metadata or the video file itself. – Erik Jun 12 '14 at 22:42
  • OK, at which point you can just define a single `AsyncTask` and pass in params to `doInBackground` which define whether it should execute methodA followed by methodB or one or the other. The problem I have with the listener / callback approach is it relies on passing in (and holding) an `Activity` `Context`. If the device is rotated the `Activity` will be destroyed and recreated with a new `Context`. – Squonk Jun 12 '14 at 22:54

1 Answers1

1

Yes. Use a Callback Listener in your Activity. As soon as this is called, you can start the new AsyncTask from your Activity.

Example in my other answer: How to return an object from the asynctask to the main class in android

Community
  • 1
  • 1
Emanuel
  • 8,027
  • 2
  • 37
  • 56