Wjdavis5
Wjdavis5

Reputation: 4151

Perform AsyncTask inside Class

I have a method inside of a class called

ChopraWisdom.GetQuote()

that pulls in some data from the interwebs. To use it I have to use an AsyncTask in my activity. Thats fine and all, but my Activity code now gets cluttered with the AsyncTask code.

I was hoping that I could hide the AsyncTask in my Class and then create another method called

ChopraWisdom.GetQuoteAsync()

But I'm not sure how to pass in "Actions" (I come from a .Net background) in order to handle the various UI updating that needs to take place.

In C# I would define the method signature as something like:

ChopraWisdom.GetQuoteAsync(Action preExecute, Action postExecute, Action updateProgress)

Questions:

  1. Does java have something comparable to 'Action'?
  2. What is the acceptable pattern for 'wrapping' Async functionality like this in Java?
  3. I like clean code, but am I being to picky here?

Please provide examples.

EDIT - Added Example class

public class ChopraWisdom
{
     public string GetQuote()
     {
        //...do stuff and return a string
     }
}

Upvotes: 2

Views: 281

Answers (2)

Thomas Eizinger
Thomas Eizinger

Reputation: 1462

  1. Java does have something comparable to Action. It is called Function and only available in Java 8. The standard way for passing a function as parameter is to create an interface and provide it as a parameter. That way you can either pass in an instance of a class implementing that interface or create an anonymous class inline. You encounter the latter everywhere in Android (OnClickListener, etc ...)

  2. I would highly recommend you to take a look at Android Annotations. It provides useful features like:

    • Dependency injection
    • View injection
    • OnClickListener via annotation
    • AsyncTask via annotation
    • ...

And the best thing: everything is done at compile time through subclassing, therefore there is no performance impact and you can check what the framework is doing at any given point.

  1. You are not too picky at all. Clean code is very important in Android development as you have to write a lot of boilerplate- / gluecode anyway.

Here are some other handy android frameworks that are definitely worth checking out:

Upvotes: 1

Stepango
Stepango

Reputation: 4841

  1. You should really think about using Loaders instead of AsynkTask(with android support lib).
  2. If you still want to use AsyncTask in your situation best way would be to create new interface Action(something like https://github.com/ReactiveX/RxJava/blob/1.x/src/main/java/rx/functions/Action0.java)
  3. You could use RxJava in your project and use all they have https://github.com/ReactiveX/RxJava/tree/1.x/src/main/java/rx/functions
  4. You could use https://github.com/evant/gradle-retrolambda in combination with (2) option to provide C# like lambdas in your java code.

Upvotes: 1

Related Questions