sealed abstract class Task[+A] extends Serializable
Task
represents a specification for a possibly lazy or
asynchronous computation, which when executed will produce an A
as a result, along with possible side-effects.
Compared with Future
from Scala's standard library, Task
does
not represent a running computation or a value detached from time,
as Task
does not execute anything when working with its builders
or operators and it does not submit any work into any thread-pool,
the execution eventually taking place only after runAsync
is
called and not before that.
Note that Task
is conservative in how it spawns logical threads.
Transformations like map
and flatMap
for example will default
to being executed on the logical thread on which the asynchronous
computation was started. But one shouldn't make assumptions about
how things will end up executed, as ultimately it is the
implementation's job to decide on the best execution model. All
you are guaranteed is asynchronous execution after executing
runAsync
.
- Self Type
- Task[A]
- Source
- Task.scala
- Alphabetic
- By Inheritance
- Task
- Serializable
- Serializable
- AnyRef
- Any
- Hide All
- Show All
- Public
- All
Value Members
-
final
def
!=(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
-
final
def
##(): Int
- Definition Classes
- AnyRef → Any
-
final
def
==(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
-
final
def
asInstanceOf[T0]: T0
- Definition Classes
- Any
-
def
asyncBoundary(s: Scheduler): Task[A]
Introduces an asynchronous boundary at the current stage in the asynchronous processing pipeline, making processing to jump on the given Scheduler (until the next async boundary).
Introduces an asynchronous boundary at the current stage in the asynchronous processing pipeline, making processing to jump on the given Scheduler (until the next async boundary).
Consider the following example:
import monix.execution.Scheduler val io = Scheduler.io() val source = Task(1).executeOn(io).map(_ + 1)
That task is being forced to execute on the
io
scheduler, including themap
transformation that follows afterexecuteOn
. But what if we want to jump with the execution run-loop on another scheduler for the following transformations?Then we can do:
import monix.execution.Scheduler.global source.asyncBoundary(global).map(_ + 2)
In this sample, whatever gets evaluated by the
source
will happen on theio
scheduler, however theasyncBoundary
call will make all subsequent operations to happen on the specifiedglobal
scheduler.- s
is the scheduler triggering the asynchronous boundary
-
def
asyncBoundary: Task[A]
Introduces an asynchronous boundary at the current stage in the asynchronous processing pipeline.
Introduces an asynchronous boundary at the current stage in the asynchronous processing pipeline.
Consider the following example:
import monix.execution.Scheduler val io = Scheduler.io() val source = Task(1).executeOn(io).map(_ + 1)
That task is being forced to execute on the
io
scheduler, including themap
transformation that follows afterexecuteOn
. But what if we want to jump with the execution run-loop on the default scheduler for the following transformations?Then we can do:
source.asyncBoundary.map(_ + 2)
In this sample, whatever gets evaluated by the
source
will happen on theio
scheduler, however theasyncBoundary
call will make all subsequent operations to happen on the default scheduler. -
def
clone(): AnyRef
- Attributes
- protected[java.lang]
- Definition Classes
- AnyRef
- Annotations
- @throws( ... )
-
def
coeval(implicit s: Scheduler): Coeval[Either[CancelableFuture[A], A]]
Transforms a Task into a Coeval that tries to execute the source synchronously, returning either
Right(value)
in case a value is available immediately, orLeft(future)
in case we have an asynchronous boundary. -
def
delayExecution(timespan: FiniteDuration): Task[A]
Returns a task that waits for the specified
timespan
before executing and mirroring the result of the source. -
def
delayExecutionWith(trigger: Task[Any]): Task[A]
Returns a task that waits for the specified
trigger
to succeed before mirroring the result of the source.Returns a task that waits for the specified
trigger
to succeed before mirroring the result of the source.If the
trigger
ends in error, then the resulting task will also end in error. -
def
delayResult(timespan: FiniteDuration): Task[A]
Returns a task that executes the source immediately on
runAsync
, but before emitting theonSuccess
result for the specified duration.Returns a task that executes the source immediately on
runAsync
, but before emitting theonSuccess
result for the specified duration.Note that if an error happens, then it is streamed immediately with no delay.
-
def
delayResultBySelector[B](selector: (A) ⇒ Task[B]): Task[A]
Returns a task that executes the source immediately on
runAsync
, but before emitting theonSuccess
result for the specified duration.Returns a task that executes the source immediately on
runAsync
, but before emitting theonSuccess
result for the specified duration.Note that if an error happens, then it is streamed immediately with no delay.
-
def
dematerialize[B](implicit ev: <:<[A, Try[B]]): Task[B]
Dematerializes the source's result from a
Try
. -
def
dematerializeAttempt[B](implicit ev: <:<[A, Attempt[B]]): Task[B]
Dematerializes the source's result from an
Attempt
. -
def
doOnCancel(callback: Task[Unit]): Task[A]
Returns a new
Task
that will mirror the source, but that will execute the givencallback
if the task gets canceled before completion.Returns a new
Task
that will mirror the source, but that will execute the givencallback
if the task gets canceled before completion.This only works for premature cancellation. See doOnFinish for triggering callbacks when the source finishes.
- callback
is the callback to execute if the task gets canceled prematurely
-
def
doOnFinish(f: (Option[Throwable]) ⇒ Task[Unit]): Task[A]
Returns a new
Task
in whichf
is scheduled to be run on completion.Returns a new
Task
in whichf
is scheduled to be run on completion. This would typically be used to release any resources acquired by thisTask
.The returned
Task
completes when both the source and the task returned byf
complete.NOTE: The given function is only called when the task is complete. However the function does not get called if the task gets canceled. Cancellation is a process that's concurrent with the execution of a task and hence needs special handling.
See doOnCancel for specifying a callback to call on canceling a task.
-
final
def
eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
-
def
equals(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
-
def
executeOn(s: Scheduler): Task[A]
Mirrors the given source
Task
, but upon execution ensure that evaluation forks into a separate (logical) thread spawned by the givenscheduler
.Mirrors the given source
Task
, but upon execution ensure that evaluation forks into a separate (logical) thread spawned by the givenscheduler
.The given Scheduler will be used for execution of the Task, effectively overriding the
Scheduler
that's passed inrunAsync
. Thus you can execute a wholeTask
on a separate thread-pool, useful for example in case of doing I/O.NOTE: the logic one cares about won't necessarily end up executed on the given scheduler, or for transformations that happen from here on. It all depends on what overrides or asynchronous boundaries happen. But this function guarantees that the this
Task
run-loop begins executing on the given scheduler.Alias for Task.fork(fa,scheduler).
- s
is the scheduler to use for execution
-
def
executeWithFork: Task[A]
Mirrors the given source
Task
, but upon execution ensure that evaluation forks into a separate (logical) thread.Mirrors the given source
Task
, but upon execution ensure that evaluation forks into a separate (logical) thread.The Scheduler used will be the one that is used to start the run-loop in
runAsync
.Alias for Task.fork(fa).
-
def
executeWithModel(em: ExecutionModel): Task[A]
Returns a new task that will execute the source with a different ExecutionModel.
Returns a new task that will execute the source with a different ExecutionModel.
This allows fine-tuning the options injected by the scheduler locally. Example:
import monix.execution.schedulers.ExecutionModel.AlwaysAsyncExecution task.executeWithModel(AlwaysAsyncExecution)
- em
is the ExecutionModel with which the source will get evaluated on
runAsync
-
def
executeWithOptions(f: (Options) ⇒ Options): Task[A]
Returns a new task that will execute the source with a different set of Options.
Returns a new task that will execute the source with a different set of Options.
This allows fine-tuning the default options. Example:
task.executeWithOptions(_.enableAutoCancelableRunLoops)
- f
is a function that takes the source's current set of options and returns a modified set of options that will be used to execute the source upon
runAsync
-
def
failed: Task[Throwable]
Returns a failed projection of this task.
Returns a failed projection of this task.
The failed projection is a future holding a value of type
Throwable
, emitting a value which is the throwable of the original task in case the original task fails, otherwise if the source succeeds, then it fails with aNoSuchElementException
. -
def
finalize(): Unit
- Attributes
- protected[java.lang]
- Definition Classes
- AnyRef
- Annotations
- @throws( classOf[java.lang.Throwable] )
-
def
flatMap[B](f: (A) ⇒ Task[B]): Task[B]
Creates a new Task by applying a function to the successful result of the source Task, and returns a task equivalent to the result of the function.
-
def
flatten[B](implicit ev: <:<[A, Task[B]]): Task[B]
Given a source Task that emits another Task, this function flattens the result, returning a Task equivalent to the emitted Task by the source.
-
def
foreach(f: (A) ⇒ Unit)(implicit s: Scheduler): CancelableFuture[Unit]
Triggers the evaluation of the source, executing the given function for the generated element.
Triggers the evaluation of the source, executing the given function for the generated element.
The application of this function has strict behavior, as the task is immediately executed.
-
def
foreachL(f: (A) ⇒ Unit): Task[Unit]
Returns a new task that upon evaluation will execute the given function for the generated element, transforming the source into a
Task[Unit]
.Returns a new task that upon evaluation will execute the given function for the generated element, transforming the source into a
Task[Unit]
.Similar in spirit with normal foreach, but lazy, as obviously nothing gets executed at this point.
-
final
def
getClass(): Class[_]
- Definition Classes
- AnyRef → Any
-
def
hashCode(): Int
- Definition Classes
- AnyRef → Any
-
final
def
isInstanceOf[T0]: Boolean
- Definition Classes
- Any
-
def
map[B](f: (A) ⇒ B): Task[B]
Returns a new Task that applies the mapping function to the element emitted by the source.
-
def
materialize: Task[Try[A]]
Creates a new Task that will expose any triggered error from the source.
-
def
materializeAttempt: Task[Attempt[A]]
Creates a new Task that will expose any triggered error from the source.
-
def
memoize: Task[A]
Memoizes the result on the computation and reuses it on subsequent invocations of
runAsync
. -
final
def
ne(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
-
final
def
notify(): Unit
- Definition Classes
- AnyRef
-
final
def
notifyAll(): Unit
- Definition Classes
- AnyRef
-
def
onErrorFallbackTo[B >: A](that: Task[B]): Task[B]
Creates a new task that in case of error will fallback to the given backup task.
-
def
onErrorHandle[U >: A](f: (Throwable) ⇒ U): Task[U]
Creates a new task that will handle any matching throwable that this task might emit.
Creates a new task that will handle any matching throwable that this task might emit.
See onErrorRecover for the version that takes a partial function.
-
def
onErrorHandleWith[B >: A](f: (Throwable) ⇒ Task[B]): Task[B]
Creates a new task that will handle any matching throwable that this task might emit by executing another task.
Creates a new task that will handle any matching throwable that this task might emit by executing another task.
See onErrorRecoverWith for the version that takes a partial function.
-
def
onErrorRecover[U >: A](pf: PartialFunction[Throwable, U]): Task[U]
Creates a new task that on error will try to map the error to another value using the provided partial function.
Creates a new task that on error will try to map the error to another value using the provided partial function.
See onErrorHandle for the version that takes a total function.
-
def
onErrorRecoverWith[B >: A](pf: PartialFunction[Throwable, Task[B]]): Task[B]
Creates a new task that will try recovering from an error by matching it with another task using the given partial function.
Creates a new task that will try recovering from an error by matching it with another task using the given partial function.
See onErrorHandleWith for the version that takes a total function.
-
def
onErrorRestart(maxRetries: Long): Task[A]
Creates a new task that in case of error will retry executing the source again and again, until it succeeds.
Creates a new task that in case of error will retry executing the source again and again, until it succeeds.
In case of continuous failure the total number of executions will be
maxRetries + 1
. -
def
onErrorRestartIf(p: (Throwable) ⇒ Boolean): Task[A]
Creates a new task that in case of error will retry executing the source again and again, until it succeeds.
Creates a new task that in case of error will retry executing the source again and again, until it succeeds.
In case of continuous failure the total number of executions will be
maxRetries + 1
. -
def
restartUntil(p: (A) ⇒ Boolean): Task[A]
Given a predicate function, keep retrying the task until the function returns true.
-
def
runAsync(implicit s: Scheduler): CancelableFuture[A]
Triggers the asynchronous execution.
Triggers the asynchronous execution.
Without invoking
runAsync
on aTask
, nothing gets evaluated, as aTask
has lazy behavior.- s
is an injected Scheduler that gets used whenever asynchronous boundaries are needed when evaluating the task
- returns
a CancelableFuture that can be used to extract the result or to cancel a running task.
-
def
runAsync(f: (Try[A]) ⇒ Unit)(implicit s: Scheduler): Cancelable
Triggers the asynchronous execution.
Triggers the asynchronous execution.
Without invoking
runAsync
on aTask
, nothing gets evaluated, as aTask
has lazy behavior.- f
is a callback that will be invoked upon completion.
- s
is an injected Scheduler that gets used whenever asynchronous boundaries are needed when evaluating the task
- returns
a Cancelable that can be used to cancel a running task
-
def
runAsync(cb: Callback[A])(implicit s: Scheduler): Cancelable
Triggers the asynchronous execution.
Triggers the asynchronous execution.
Without invoking
runAsync
on aTask
, nothing gets evaluated, as aTask
has lazy behavior.- cb
is a callback that will be invoked upon completion.
- s
is an injected Scheduler that gets used whenever asynchronous boundaries are needed when evaluating the task
- returns
a Cancelable that can be used to cancel a running task
-
final
def
synchronized[T0](arg0: ⇒ T0): T0
- Definition Classes
- AnyRef
-
def
timeout(after: FiniteDuration): Task[A]
Returns a Task that mirrors the source Task but that triggers a
TimeoutException
in case the given duration passes without the task emitting any item. -
def
timeoutTo[B >: A](after: FiniteDuration, backup: Task[B]): Task[B]
Returns a Task that mirrors the source Task but switches to the given backup Task in case the given duration passes without the source emitting any item.
-
def
toReactivePublisher[B >: A](implicit s: Scheduler): Publisher[B]
Converts a Task to an
org.reactivestreams.Publisher
that emits a single item on success, or just the error on failure.Converts a Task to an
org.reactivestreams.Publisher
that emits a single item on success, or just the error on failure.See reactive-streams.org for the Reactive Streams specification.
-
def
toString(): String
- Definition Classes
- AnyRef → Any
-
final
def
wait(): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws( ... )
-
final
def
wait(arg0: Long, arg1: Int): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws( ... )
-
final
def
wait(arg0: Long): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws( ... )
-
def
zip[B](that: Task[B]): Task[(A, B)]
Zips the values of
this
andthat
task, and creates a new task that will emit the tuple of their results. -
def
zipMap[B, C](that: Task[B])(f: (A, B) ⇒ C): Task[C]
Zips the values of
this
andthat
and applies the given mapping function on their results.
This is the API documentation for the Monix library.
Package Overview
monix.execution exposes lower level primitives for dealing with asynchronous execution:
Atomic
types, as alternative tojava.util.concurrent.atomic
monix.eval is for dealing with evaluation of results, thus exposing Task and Coeval.
monix.reactive exposes the
Observable
pattern:Observable
implementationsmonix.types implements type-class shims, to be translated to type-classes provided by libraries such as Cats or Scalaz.
monix.cats is the optional integration with the Cats library, providing translations for the types described in
monix.types
.monix.scalaz is the optional integration with the Scalaz library, providing translations for the types described in
monix.types
.