Module: MotionAsync

Defined in:
lib/motion-async/motion_async.rb,
lib/motion-async/version.rb

Overview

MotionAsync provides a friendly Ruby wrapper around Android’s AsyncTask.

You can call it directly:

Or include the module to make the async command available wherever you need it

Usage:

Run a block of code in the background:

Specify a block to execute when the operation completes. The return value of the async block is passed in as a parameter:

Alternate syntax for the same example:

For progress updates, provide a :progress block, and periodically call #progress on the task object in the :background block. The :progress block is executed on the main thread.

:pre_execute is invoked before the async operation begins and :cancelled is called if the task is cancelled.

async returns a reference to the task object (a subclass of AsyncTask); you can hold on to this in case you want to cancel it later. You can see if a task has been cancelled by calling cancelled?

end … def on_stop

@async_task.cancel

end

Examples:

MotionAsync.async do
  # some long task
end
include MotionAsync
...
async do
  # some long task
end
async do
  # some long operation
end
task = async do
  some_expensive_calculation()
end
task.on :completion do |result|
  p "The result was #{result}"
end
async.on(:background) do |task|
  some_expensive_calculation()
end.on(:completion) do |result|
  p "The result was #{result}"
end
async.on(:background) do |task|
  100.times do |i|
    # do some work
    task.progress i
  end
end.on(:progress) do |result|
  p "Progress: #{progress + 1}% complete"
end
async.on(:background) do |task|
  # long operation
end.on(:pre_execute) do
  p "About to run a long operation"
end.on(:cancelled) do
  p "Operation cancelled."
end

Constant Summary collapse

VERSION =
"0.5"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.async(options = {}, &block) ⇒ Object



92
93
94
95
96
# File 'lib/motion-async/motion_async.rb', line 92

def self.async(options={}, &block)
  MotionAsyncTask.create(options, &block).tap do |task|
    task.execute []
  end
end

Instance Method Details

#async(options = {}, &block) ⇒ Object



98
99
100
# File 'lib/motion-async/motion_async.rb', line 98

def async(options={}, &block)
  MotionAsync.async(options, &block)
end