-
Notifications
You must be signed in to change notification settings - Fork 37
Basics
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.
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.
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;
}
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.
Created by Joan Zapata.
- Learn the basics.
- How to [enhance your service](Enhance Service).
- Take advantage of [caching](Caching Patterns).
- How to [handle exceptions](Handle Exceptions).
- Want more? See what's [behind the scenes](Behind The Scenes).