Creating Your Own Operation
Larger operations, such as database access or remote communication, often require a lot of time and must therefore be performed in a thread different from the main thread so that the responsiveness of the user interface is not blocked. Mobile Development provides the AbstractThreadedOperation class, which can be used to create asynchronous, thread-safe operations. This class creates its own thread once it is executed and provides thread-safe notifications. The following snippet shows how to create a subclass:
import com.softwareag.mobile.runtime.toolkit.operations.AbstractThreadedOperation;
public class MyOperation extends AbstractThreadedOperation {
protected void runInternal() throws Exception {
// put code here, let's have exceptions being thrown
}
}
To extend AbstractThreadedOperation, you need to put logic into runInternal(). This method is executed after AbstractThreadedOperation#execute() has been called. Because AbstractThreadedOperation inherits from IOperation, it is possible to attach multiple IOperationDelegate classes for being notified of the operation's state. The following snippet shows how to start the operation and how to add listeners:
final MyOperation operation = new MyOperation();
operation.addOperationDelegate(new IOperationDelegate() {
public void onOperationFinished(final IOperation operation) {
}
public void onOperationFailed(final IOperation operation) {
}
});
operation.execute();
It is recommended to add the delegates before executing the operation. The IOperationDelegate#onOperationFinished(IOperation) method is called after runInternal() has completed without any exception. If an exception is thrown, onOperationFailed is called. The result of the operation can be set using the protected member AbstractThreadedOperation#result.
Related Topics