Skip to content
Joan Zapata edited this page Jan 8, 2015 · 12 revisions

First service

Here's a basic AsyncService. All you need is a basic java class annotated with @AsyncService:

@AsyncService
public class DemoService {

    public User getUser(String name) {
        return ...;
    }

}
Rule #1: By default, all methods in a AsyncService runs in a background thread, one after the other. It's a safe place to make network call, IO operations and other long running tasks.
Rule #2: Keep in mind that if you return null from a method in a AsyncService, no message is sent back to the caller.

Initialization

You need to be aware that your service is not a singleton. This is because it needs to know at anytime where it has been injected, in other words who is the source of any message sent by your service. To avoid duplication of complex objects, all fields must be static. You can use @Init to initialize them, but make sure it's static too.

@AsyncService
public class DemoService {

   static RestClient restClient;

   @Init
   static void init(){
       // Initialize the rest client here
   }

}
Rule #3: Because it's not a singleton, all field in an AsyncService should be static. To avoid confusion, a compile error will be thrown if you try to use a non-static field, or a non-static @Init method.

Context

If you need a context in your service, avoid creating a setter, it could be dangerous if you retain an Activity context statically. Using @ApplicationContext, you're safe.

@AsyncService
public class DemoService {

   @ApplicationContext
   static Context context;

}

Usage

You've seen how to create your first service. Let's use it in an activity in 4 steps!

public class DemoActivity extends Activity {

   // Step 1: Declare the service
   @InjectService DemoService service;

   @Override
   public void onCreate(Bundle bundle){
      super.onCreate(bundle);

      // Step 2: Inject the service
      AsyncService.inject(this);

      // Step 3: Call one of your method on your service
      service.getUser("Joan");
      
   }

   // Step 4: Declare where you receive the result
   @OnMessage public void onUser(User user){
      ...
   }
}

By default, Step 3 and 4 are linked in a private box, that means you can only receive messages in response to method calls from the same activity.

Caller private box illustration

Rule #4: A caller only receive the messages originated from its own requests by default. If you want to receive results from anywhere, you can use @OnMessage(from = ALL). You can use that to make a global listener or logger for example.

Next step: [enhance your service](Enhance Service)