object Task extends TaskInstancesLevel1 with Serializable
Builders for Task.
- Alphabetic
- By Inheritance
- Task
- Serializable
- Serializable
- TaskInstancesLevel1
- TaskInstancesLevel0
- TaskParallelNewtype
- TaskTimers
- AnyRef
- Any
- Hide All
- Show All
- Public
- All
Type Members
-
final
case class
Context(scheduler: Scheduler, options: Options, connection: StackedCancelable, frameRef: FrameIndexRef) extends Product with Serializable
The
Contextunder which Task is supposed to be executed.The
Contextunder which Task is supposed to be executed.This definition is of interest only when creating tasks with Task.unsafeCreate, which exposes internals and is considered unsafe to use.
- scheduler
is the Scheduler in charge of evaluation on
runAsync.- options
is a set of options for customizing the task's behavior upon evaluation.
- connection
is the StackedCancelable that handles the cancellation on
runAsync- frameRef
is a thread-local counter that keeps track of the current frame index of the run-loop. The run-loop is supposed to force an asynchronous boundary upon reaching a certain threshold, when the task is evaluated with monix.execution.ExecutionModel.BatchedExecution. And this
frameIndexRefshould be reset whenever a real asynchronous boundary happens. See the description of FrameIndexRef.
- implicit final class DeprecatedExtensions[A] extends AnyVal
-
type
FrameIndex = Int
A run-loop frame index is a number representing the current run-loop cycle, being incremented whenever a
flatMapevaluation happens.A run-loop frame index is a number representing the current run-loop cycle, being incremented whenever a
flatMapevaluation happens.It gets used for automatically forcing asynchronous boundaries, according to the ExecutionModel injected by the Scheduler when the task gets evaluated with
runAsync.- See also
-
sealed abstract
class
FrameIndexRef extends AnyRef
A reference that boxes a FrameIndex possibly using a thread-local.
A reference that boxes a FrameIndex possibly using a thread-local.
This definition is of interest only when creating tasks with Task.unsafeCreate, which exposes internals and is considered unsafe to use.
In case the Task is executed with BatchedExecution, this class boxes a FrameIndex in order to transport it over light async boundaries, possibly using a ThreadLocal, since this index is not supposed to survive when threads get forked.
The FrameIndex is a counter that increments whenever a
flatMapoperation is evaluated. And withBatchedExecution, whenever that counter exceeds the specified threshold, an asynchronous boundary is automatically inserted. However this capability doesn't blend well with light asynchronous boundaries, for exampleAsynctasks that never fork logical threads or TrampolinedRunnable instances executed by capable schedulers. This is why FrameIndexRef is part of the Context of execution for Task, available for asynchronous tasks that get created with Task.unsafeCreate.Note that in case the execution model is not BatchedExecution then this reference is just a dummy, since there's no point in keeping a counter around, plus setting and fetching from a
ThreadLocalcan be quite expensive. -
final
case class
Options(autoCancelableRunLoops: Boolean, localContextPropagation: Boolean) extends Product with Serializable
Set of options for customizing the task's behavior.
Set of options for customizing the task's behavior.
See Task.defaultOptions for the default
Optionsinstance used by .runAsync.- autoCancelableRunLoops
should be set to
truein case you wantflatMapdriven loops to be auto-cancelable. Defaults tofalse.- localContextPropagation
should be set to
truein case you want the Local variables to be propagated on async boundaries. Defaults tofalse.
-
type
Par[+A] = TaskParallelNewtype.Par.Type[A]
Newtype encoding for an
Taskdatatype that has a cats.Applicative capable of doing parallel processing inapandmap2, needed for implementing cats.Parallel.Newtype encoding for an
Taskdatatype that has a cats.Applicative capable of doing parallel processing inapandmap2, needed for implementing cats.Parallel.Helpers are provided for converting back and forth in
Par.applyfor wrapping anyTaskvalue andPar.unwrapfor unwrapping.The encoding is based on the "newtypes" project by Alexander Konovalov, chosen because it's devoid of boxing issues and a good choice until opaque types will land in Scala.
- Definition Classes
- TaskParallelNewtype
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
-
def
apply[A](f: ⇒ A): Task[A]
Returns a new task that, when executed, will emit the result of the given function, executed asynchronously.
Returns a new task that, when executed, will emit the result of the given function, executed asynchronously.
This operation is the equivalent of:
Task.eval(f).executeAsync
- f
is the callback to execute asynchronously
-
final
def
asInstanceOf[T0]: T0
- Definition Classes
- Any
-
def
async[A](register: (Scheduler, Callback[A]) ⇒ Cancelable): Task[A]
Create a
Taskfrom an asynchronous computation, which takes the form of a function with which we can register a callback.Create a
Taskfrom an asynchronous computation, which takes the form of a function with which we can register a callback.This can be used to translate from a callback-based API to a straightforward monadic version.
Alias for Task.create.
- register
is a function that will be called when this
Taskis executed, receiving a callback as a parameter, a callback that the user is supposed to call in order to signal the desired outcome of thisTask.
-
implicit
def
catsAsync: CatsConcurrentForTask
Global instance for
cats.effect.Asyncand forcats.effect.Concurrent.Global instance for
cats.effect.Asyncand forcats.effect.Concurrent.Implied are also
cats.CoflatMap,cats.Applicative,cats.Monad,cats.MonadErrorandcats.effect.Sync.As trivia, it's named "catsAsync" and not "catsConcurrent" because it represents the
cats.effect.Asynclineage, up untilcats.effect.Effect, which imposes extra restrictions, in our case the need for aSchedulerto be in scope (see Task.catsEffect). So by naming the lineage, not the concrete sub-type implemented, we avoid breaking compatibility whenever a new type class (that we can implement) gets added into Cats.Seek more info about Cats, the standard library for FP, at:
- Definition Classes
- TaskInstancesLevel1
-
implicit
def
catsEffect(implicit s: Scheduler): CatsConcurrentEffectForTask
Global instance for
cats.effect.Effectand forcats.effect.ConcurrentEffect.Global instance for
cats.effect.Effectand forcats.effect.ConcurrentEffect.Implied are
cats.CoflatMap,cats.Applicative,cats.Monad,cats.MonadError,cats.effect.Syncandcats.effect.Async.Note this is different from Task.catsAsync because we need an implicit Scheduler in scope in order to trigger the execution of a
Task. It's also lower priority in order to not trigger conflicts, becauseEffect <: AsyncandConcurrentEffect <: Concurrent with Effect.As trivia, it's named "catsEffect" and not "catsConcurrentEffect" because it represents the
cats.effect.Effectlineage, as in the minimum that this value will support in the future. So by naming the lineage, not the concrete sub-type implemented, we avoid breaking compatibility whenever a new type class (that we can implement) gets added into Cats.Seek more info about Cats, the standard library for FP, at:
- s
is a Scheduler that needs to be available in scope
- Definition Classes
- TaskInstancesLevel0
-
implicit
def
catsMonoid[A](implicit A: Monoid[A]): Monoid[Task[A]]
Given an
Atype that has acats.Monoid[A]implementation, then this provides the evidence thatTask[A]also has aMonoid[Task[A]]implementation.Given an
Atype that has acats.Monoid[A]implementation, then this provides the evidence thatTask[A]also has aMonoid[Task[A]]implementation.- Definition Classes
- TaskInstancesLevel1
-
implicit
def
catsParallel: CatsParallelForTask
Global instance for
cats.Parallel.Global instance for
cats.Parallel.The
Paralleltype class is useful for processing things in parallel in a generic way, usable with Cats' utils and syntax:import cats.syntax.all._ (taskA, taskB, taskC).parMap { (a, b, c) => a + b + c }
Seek more info about Cats, the standard library for FP, at:
- Definition Classes
- TaskInstancesLevel1
-
implicit
def
catsSemigroup[A](implicit A: Semigroup[A]): Semigroup[Task[A]]
Given an
Atype that has acats.Semigroup[A]implementation, then this provides the evidence thatTask[A]also has aSemigroup[Task[A]]implementation.Given an
Atype that has acats.Semigroup[A]implementation, then this provides the evidence thatTask[A]also has aSemigroup[Task[A]]implementation.This has a lower-level priority than Task.catsMonoid in order to avoid conflicts.
- Definition Classes
- TaskInstancesLevel0
-
def
clone(): AnyRef
- Attributes
- protected[java.lang]
- Definition Classes
- AnyRef
- Annotations
- @native() @throws( ... )
- def coeval[A](a: Coeval[A]): Task[A]
-
def
create[A](register: (Scheduler, Callback[A]) ⇒ Cancelable): Task[A]
Create a
Taskfrom an asynchronous computation, which takes the form of a function with which we can register a callback.Create a
Taskfrom an asynchronous computation, which takes the form of a function with which we can register a callback.This can be used to translate from a callback-based API to a straightforward monadic version.
- register
is a function that will be called when this
Taskis executed, receiving a callback as a parameter, a callback that the user is supposed to call in order to signal the desired outcome of thisTask.
-
val
defaultOptions: Options
Default Options to use for Task evaluation, thus:
Default Options to use for Task evaluation, thus:
autoCancelableRunLoopsisfalseby defaultlocalContextPropagationisfalseby default
On top of the JVM the default can be overridden by setting the following system properties:
monix.environment.autoCancelableRunLoops(true,yesor1for enabling)monix.environment.localContextPropagation(true,yesor1for enabling)
- See also
-
def
defer[A](fa: ⇒ Task[A]): Task[A]
Promote a non-strict value representing a Task to a Task of the same type.
-
def
deferAction[A](f: (Scheduler) ⇒ Task[A]): Task[A]
Defers the creation of a
Taskby using the provided function, which has the ability to inject a needed Scheduler.Defers the creation of a
Taskby using the provided function, which has the ability to inject a needed Scheduler.Example:
def measureLatency[A](source: Task[A]): Task[(A, Long)] = Task.deferAction { implicit s => // We have our Scheduler, which can inject time, we // can use it for side-effectful operations val start = s.currentTimeMillis() source.map { a => val finish = s.currentTimeMillis() (a, finish - start) } }
- f
is the function that's going to be called when the resulting
Taskgets evaluated
-
def
deferFuture[A](fa: ⇒ Future[A]): Task[A]
Promote a non-strict Scala
Futureto aTaskof the same type.Promote a non-strict Scala
Futureto aTaskof the same type.The equivalent of doing:
Task.defer(Task.fromFuture(fa))
-
def
deferFutureAction[A](f: (Scheduler) ⇒ Future[A]): Task[A]
Wraps calls that generate
Futureresults into Task, provided a callback with an injected Scheduler to act as the necessaryExecutionContext.Wraps calls that generate
Futureresults into Task, provided a callback with an injected Scheduler to act as the necessaryExecutionContext.This builder helps with wrapping
Future-enabled APIs that need an implicitExecutionContextto work. Consider this example:import scala.concurrent.{ExecutionContext, Future} def sumFuture(list: Seq[Int])(implicit ec: ExecutionContext): Future[Int] = Future(list.sum)
We'd like to wrap this function into one that returns a lazy
Taskthat evaluates this sum every time it is called, because that's how tasks work best. However in order to invoke this function anExecutionContextis needed:def sumTask(list: Seq[Int])(implicit ec: ExecutionContext): Task[Int] = Task.deferFuture(sumFuture(list))
But this is not only superfluous, but against the best practices of using
Task. The difference is thatTasktakes a Scheduler (inheriting fromExecutionContext) only when runAsync happens. But withdeferFutureActionwe get to have an injectedSchedulerin the passed callback:def sumTask(list: Seq[Int]): Task[Int] = Task.deferFutureAction { implicit scheduler => sumFuture(list) }
- f
is the function that's going to be executed when the task gets evaluated, generating the wrapped
Future
-
def
delay[A](a: ⇒ A): Task[A]
Alias for eval.
-
final
def
eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
-
def
equals(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
-
def
eval[A](a: ⇒ A): Task[A]
Promote a non-strict value to a Task, catching exceptions in the process.
Promote a non-strict value to a Task, catching exceptions in the process.
Note that since
Taskis not memoized, this will recompute the value each time theTaskis executed. -
def
evalOnce[A](a: ⇒ A): Task[A]
Promote a non-strict value to a Task that is memoized on the first evaluation, the result being then available on subsequent evaluations.
-
def
finalize(): Unit
- Attributes
- protected[java.lang]
- Definition Classes
- AnyRef
- Annotations
- @throws( classOf[java.lang.Throwable] )
-
def
fromEffect[F[_], A](fa: F[A])(implicit F: Effect[F]): Task[A]
Builds a Task instance out of any data type that implements either
cats.effect.ConcurrentEffectorcats.effect.Effect.Builds a Task instance out of any data type that implements either
cats.effect.ConcurrentEffectorcats.effect.Effect.This method discriminates between
EffectandConcurrentEffectusing their subtype encoding (ConcurrentEffect <: Effect), such that:- if the indicated type has a
ConcurrentEffectimplementation and if the indicated value is cancelable, then the resulting task is also cancelable - otherwise, if the indicated type only implements
Effect, then the conversion is still possible, but the resulting task isn't cancelable
Example:
import cats.effect._ import cats.syntax.all._ val io = Timer[IO].sleep(5.seconds) *> IO(println("Hello!")) // Resulting task is cancelable val task: Task[Unit] = Task.fromEffect(io)
- F
is the
cats.effect.Effecttype class instance necessary for converting toTask; this instance can also be acats.effect.Concurrent, in which case the resultingTaskvalue is cancelable if the source is
- if the indicated type has a
-
def
fromEval[A](a: cats.Eval[A]): Task[A]
Builds a Task instance out of a
cats.Eval. -
def
fromFuture[A](f: Future[A]): Task[A]
Converts the given Scala
Futureinto aTask.Converts the given Scala
Futureinto aTask.NOTE: if you want to defer the creation of the future, use in combination with defer.
-
def
fromIO[A](ioa: IO[A]): Task[A]
Converts
IO[A]values intoTask[A].Converts
IO[A]values intoTask[A].Preserves cancelability, if the source
IOvalue is cancelable.import cats.effect._ import cats.syntax.all._ import scala.concurrent.duration._ val io: IO[Unit] = IO.sleep(5.seconds) *> IO(println("Hello!")) // Conversion; note the resulting task is also // cancelable if the source is val task: Task[Unit] = Task.fromIO(ioa)
Also see fromEffect, the more generic conversion utility.
-
def
fromTry[A](a: Try[A]): Task[A]
Builds a Task instance out of a Scala
Try. -
def
gather[A, M[X] <: TraversableOnce[X]](in: M[Task[A]])(implicit cbf: CanBuildFrom[M[Task[A]], A, M[A]]): Task[M[A]]
Nondeterministically gather results from the given collection of tasks, returning a task that will signal the same type of collection of results once all tasks are finished.
Nondeterministically gather results from the given collection of tasks, returning a task that will signal the same type of collection of results once all tasks are finished.
This function is the nondeterministic analogue of
sequenceand should behave identically tosequenceso long as there is no interaction between the effects being gathered. However, unlikesequence, which decides on a total order of effects, the effects in agatherare unordered with respect to each other.Although the effects are unordered, we ensure the order of results matches the order of the input sequence. Also see gatherUnordered for the more efficient alternative.
-
def
gatherUnordered[A](in: TraversableOnce[Task[A]]): Task[List[A]]
Nondeterministically gather results from the given collection of tasks, without keeping the original ordering of results.
Nondeterministically gather results from the given collection of tasks, without keeping the original ordering of results.
If the tasks in the list are set to execute asynchronously, forking logical threads, then the tasks will execute in parallel.
This function is similar to gather, but neither the effects nor the results will be ordered. Useful when you don't need ordering because:
- it has non-blocking behavior (but not wait-free)
- it can be more efficient (compared with gather), but not necessarily (if you care about performance, then test)
- in
is a list of tasks to execute
-
final
def
getClass(): Class[_]
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
-
def
hashCode(): Int
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
-
final
def
isInstanceOf[T0]: Boolean
- Definition Classes
- Any
-
def
map2[A1, A2, R](fa1: Task[A1], fa2: Task[A2])(f: (A1, A2) ⇒ R): Task[R]
Pairs 2
Taskvalues, applying the given mapping function.Pairs 2
Taskvalues, applying the given mapping function.Returns a new
Taskreference that completes with the result of mapping that function to their successful results, or in failure in case either of them fails.This is a specialized Task.sequence operation and as such the tasks are evaluated in order, one after another, the operation being described in terms of .flatMap.
val fa1 = Task(1) val fa2 = Task(2) // Yields Success(3) Task.map2(fa1, fa2) { (a, b) => a + b } // Yields Failure(e), because the second arg is a failure Task.map2(fa1, Task.raiseError(e)) { (a, b) => a + b }
See Task.parMap2 for parallel processing.
-
def
map3[A1, A2, A3, R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3])(f: (A1, A2, A3) ⇒ R): Task[R]
Pairs 3
Taskvalues, applying the given mapping function.Pairs 3
Taskvalues, applying the given mapping function.Returns a new
Taskreference that completes with the result of mapping that function to their successful results, or in failure in case either of them fails.This is a specialized Task.sequence operation and as such the tasks are evaluated in order, one after another, the operation being described in terms of .flatMap.
val fa1 = Task(1) val fa2 = Task(2) val fa3 = Task(3) // Yields Success(6) Task.map3(fa1, fa2, fa3) { (a, b, c) => a + b + c } // Yields Failure(e), because the second arg is a failure Task.map3(fa1, Task.raiseError(e), fa3) { (a, b, c) => a + b + c }
See Task.parMap3 for parallel processing.
-
def
map4[A1, A2, A3, A4, R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4])(f: (A1, A2, A3, A4) ⇒ R): Task[R]
Pairs 4
Taskvalues, applying the given mapping function.Pairs 4
Taskvalues, applying the given mapping function.Returns a new
Taskreference that completes with the result of mapping that function to their successful results, or in failure in case either of them fails.This is a specialized Task.sequence operation and as such the tasks are evaluated in order, one after another, the operation being described in terms of .flatMap.
val fa1 = Task(1) val fa2 = Task(2) val fa3 = Task(3) val fa4 = Task(4) // Yields Success(10) Task.map4(fa1, fa2, fa3, fa4) { (a, b, c, d) => a + b + c + d } // Yields Failure(e), because the second arg is a failure Task.map4(fa1, Task.raiseError(e), fa3, fa4) { (a, b, c, d) => a + b + c + d }
See Task.parMap4 for parallel processing.
-
def
map5[A1, A2, A3, A4, A5, R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5])(f: (A1, A2, A3, A4, A5) ⇒ R): Task[R]
Pairs 5
Taskvalues, applying the given mapping function.Pairs 5
Taskvalues, applying the given mapping function.Returns a new
Taskreference that completes with the result of mapping that function to their successful results, or in failure in case either of them fails.This is a specialized Task.sequence operation and as such the tasks are evaluated in order, one after another, the operation being described in terms of .flatMap.
val fa1 = Task(1) val fa2 = Task(2) val fa3 = Task(3) val fa4 = Task(4) val fa5 = Task(5) // Yields Success(15) Task.map5(fa1, fa2, fa3, fa4, fa5) { (a, b, c, d, e) => a + b + c + d + e } // Yields Failure(e), because the second arg is a failure Task.map5(fa1, Task.raiseError(e), fa3, fa4, fa5) { (a, b, c, d, e) => a + b + c + d + e }
See Task.parMap5 for parallel processing.
-
def
map6[A1, A2, A3, A4, A5, A6, R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5], fa6: Task[A6])(f: (A1, A2, A3, A4, A5, A6) ⇒ R): Task[R]
Pairs 6
Taskvalues, applying the given mapping function.Pairs 6
Taskvalues, applying the given mapping function.Returns a new
Taskreference that completes with the result of mapping that function to their successful results, or in failure in case either of them fails.This is a specialized Task.sequence operation and as such the tasks are evaluated in order, one after another, the operation being described in terms of .flatMap.
val fa1 = Task(1) val fa2 = Task(2) val fa3 = Task(3) val fa4 = Task(4) val fa5 = Task(5) val fa6 = Task(6) // Yields Success(21) Task.map6(fa1, fa2, fa3, fa4, fa5, fa6) { (a, b, c, d, e, f) => a + b + c + d + e + f } // Yields Failure(e), because the second arg is a failure Task.map6(fa1, Task.raiseError(e), fa3, fa4, fa5, fa6) { (a, b, c, d, e, f) => a + b + c + d + e + f }
See Task.parMap6 for parallel processing.
-
def
mapBoth[A1, A2, R](fa1: Task[A1], fa2: Task[A2])(f: (A1, A2) ⇒ R): Task[R]
Apply a mapping functions to the results of two tasks, nondeterministically ordering their effects.
Apply a mapping functions to the results of two tasks, nondeterministically ordering their effects.
If the two tasks are synchronous, they'll get executed one after the other, with the result being available asynchronously. If the two tasks are asynchronous, they'll get scheduled for execution at the same time and in a multi-threading environment they'll execute in parallel and have their results synchronized.
-
final
def
ne(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
-
def
never[A]: Task[A]
A Task instance that upon evaluation will never complete.
-
final
def
notify(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native()
-
final
def
notifyAll(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native()
-
def
now[A](a: A): Task[A]
Returns a
Taskthat on execution is always successful, emitting the given strict value. -
def
parMap2[A1, A2, R](fa1: Task[A1], fa2: Task[A2])(f: (A1, A2) ⇒ R): Task[R]
Pairs 2
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.Pairs 2
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.This is a specialized Task.gather operation and as such the tasks are evaluated in parallel, ordering the results. In case one of the tasks fails, then all other tasks get cancelled and the final result will be a failure.
val fa1 = Task(1) val fa2 = Task(2) // Yields Success(3) Task.parMap2(fa1, fa2) { (a, b) => a + b } // Yields Failure(e), because the second arg is a failure Task.parMap2(fa1, Task.raiseError(e)) { (a, b) => a + b }
See Task.map2 for sequential processing.
-
def
parMap3[A1, A2, A3, R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3])(f: (A1, A2, A3) ⇒ R): Task[R]
Pairs 3
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.Pairs 3
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.This is a specialized Task.gather operation and as such the tasks are evaluated in parallel, ordering the results. In case one of the tasks fails, then all other tasks get cancelled and the final result will be a failure.
val fa1 = Task(1) val fa2 = Task(2) val fa3 = Task(3) // Yields Success(6) Task.parMap3(fa1, fa2, fa3) { (a, b, c) => a + b + c } // Yields Failure(e), because the second arg is a failure Task.parMap3(fa1, Task.raiseError(e), fa3) { (a, b, c) => a + b + c }
See Task.map3 for sequential processing.
-
def
parMap4[A1, A2, A3, A4, R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4])(f: (A1, A2, A3, A4) ⇒ R): Task[R]
Pairs 4
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.Pairs 4
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.This is a specialized Task.gather operation and as such the tasks are evaluated in parallel, ordering the results. In case one of the tasks fails, then all other tasks get cancelled and the final result will be a failure.
val fa1 = Task(1) val fa2 = Task(2) val fa3 = Task(3) val fa4 = Task(4) // Yields Success(10) Task.parMap4(fa1, fa2, fa3, fa4) { (a, b, c, d) => a + b + c + d } // Yields Failure(e), because the second arg is a failure Task.parMap4(fa1, Task.raiseError(e), fa3, fa4) { (a, b, c, d) => a + b + c + d }
See Task.map4 for sequential processing.
-
def
parMap5[A1, A2, A3, A4, A5, R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5])(f: (A1, A2, A3, A4, A5) ⇒ R): Task[R]
Pairs 5
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.Pairs 5
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.This is a specialized Task.gather operation and as such the tasks are evaluated in parallel, ordering the results. In case one of the tasks fails, then all other tasks get cancelled and the final result will be a failure.
val fa1 = Task(1) val fa2 = Task(2) val fa3 = Task(3) val fa4 = Task(4) val fa5 = Task(5) // Yields Success(15) Task.parMap5(fa1, fa2, fa3, fa4, fa5) { (a, b, c, d, e) => a + b + c + d + e } // Yields Failure(e), because the second arg is a failure Task.parMap5(fa1, Task.raiseError(e), fa3, fa4, fa5) { (a, b, c, d, e) => a + b + c + d + e }
See Task.map5 for sequential processing.
-
def
parMap6[A1, A2, A3, A4, A5, A6, R](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5], fa6: Task[A6])(f: (A1, A2, A3, A4, A5, A6) ⇒ R): Task[R]
Pairs 6
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.Pairs 6
Taskvalues, applying the given mapping function, ordering the results, but not the side effects, the evaluation being done in parallel if the tasks are async.This is a specialized Task.gather operation and as such the tasks are evaluated in parallel, ordering the results. In case one of the tasks fails, then all other tasks get cancelled and the final result will be a failure.
val fa1 = Task(1) val fa2 = Task(2) val fa3 = Task(3) val fa4 = Task(4) val fa5 = Task(5) val fa6 = Task(6) // Yields Success(21) Task.parMap6(fa1, fa2, fa3, fa4, fa5, fa6) { (a, b, c, d, e, f) => a + b + c + d + e + f } // Yields Failure(e), because the second arg is a failure Task.parMap6(fa1, Task.raiseError(e), fa3, fa4, fa5, fa6) { (a, b, c, d, e, f) => a + b + c + d + e + f }
See Task.map6 for sequential processing.
-
def
pure[A](a: A): Task[A]
Lifts a value into the task context.
Lifts a value into the task context. Alias for now.
-
def
race[A, B](fa: Task[A], fb: Task[B]): Task[Either[A, B]]
Run two
Taskactions concurrently, and return the first to finish, either in success or error.Run two
Taskactions concurrently, and return the first to finish, either in success or error. The loser of the race is cancelled.The two tasks are executed in parallel, the winner being the first that signals a result.
As an example, this would be equivalent with Task.timeout:
import scala.concurrent.duration._ val timeoutError = Task .raiseError(new TimeoutException) .delayExecution(5.seconds) Task.race(myTask, timeoutError)
Similarly Task.timeoutTo is expressed in terms of
race.Also see racePair for a version that does not cancel the loser automatically on successful results. And raceMany for a version that races a whole list of tasks.
-
def
raceMany[A](tasks: TraversableOnce[Task[A]]): Task[A]
Runs multiple
Taskactions concurrently, returning the first to finish, either in success or error.Runs multiple
Taskactions concurrently, returning the first to finish, either in success or error. All losers of the race get cancelled.The tasks get executed in parallel, the winner being the first that signals a result.
val list: List[Task[Int]] = List(t1, t2, t3, ???) val winner: Task[Int] = Task.raceMany(list)
See race or racePair for racing two tasks, for more control.
-
def
racePair[A, B](fa: Task[A], fb: Task[B]): Task[Either[(A, Fiber[B]), (Fiber[A], B)]]
Run two
Taskactions concurrently, and returns a pair containing both the winner's successful value and the loser represented as a still-unfinished task.Run two
Taskactions concurrently, and returns a pair containing both the winner's successful value and the loser represented as a still-unfinished task.If the first task completes in error, then the result will complete in error, the other task being cancelled.
On usage the user has the option of cancelling the losing task, this being equivalent with plain race:
val ta: Task[A] = ??? val tb: Task[B] = ??? Task.racePair(ta, tb).flatMap { case Left((a, taskB)) => taskB.cancel.map(_ => a) case Right((taskA, b)) => taskA.cancel.map(_ => b) }
See race for a simpler version that cancels the loser immediately or raceMany that races collections of tasks.
-
def
raiseError[A](ex: Throwable): Task[A]
Returns a task that on execution is always finishing in error emitting the specified exception.
-
def
sequence[A, M[X] <: TraversableOnce[X]](in: M[Task[A]])(implicit cbf: CanBuildFrom[M[Task[A]], A, M[A]]): Task[M[A]]
Given a
TraversableOnceof tasks, transforms it to a task signaling the collection, executing the tasks one by one and gathering their results in the same collection.Given a
TraversableOnceof tasks, transforms it to a task signaling the collection, executing the tasks one by one and gathering their results in the same collection.This operation will execute the tasks one by one, in order, which means that both effects and results will be ordered. See gather and gatherUnordered for unordered results or effects, and thus potential of running in parallel.
It's a simple version of traverse.
-
def
shift(ec: ExecutionContext): Task[Unit]
Asynchronous boundary described as an effectful
Taskthat can be used inflatMapchains to "shift" the continuation of the run-loop to another call stack or thread, managed by the given execution context.Asynchronous boundary described as an effectful
Taskthat can be used inflatMapchains to "shift" the continuation of the run-loop to another call stack or thread, managed by the given execution context.This is the equivalent of
IO.shift.For example we can introduce an asynchronous boundary in the
flatMapchain before a certain task, this being literally the implementation of executeAsync:Task.shift.flatMap(_ => task)And this can also be described with
followedByfrom Cats:import cats.syntax.all._ Task.shift.followedBy(task)Or we can specify an asynchronous boundary after the evaluation of a certain task, this being literally the implementation of .asyncBoundary:
task.flatMap(a => Task.shift.map(_ => a))
And again we can also describe this with
forEffectfrom Cats:task.forEffect(Task.shift)
-
final
val
shift: Task[Unit]
Asynchronous boundary described as an effectful
Taskthat can be used inflatMapchains to "shift" the continuation of the run-loop to another thread or call stack, managed by the default Scheduler.Asynchronous boundary described as an effectful
Taskthat can be used inflatMapchains to "shift" the continuation of the run-loop to another thread or call stack, managed by the default Scheduler.This is the equivalent of
IO.shift, except that Monix'sTaskgets executed with an injectedSchedulerin .runAsync and that's going to be theSchedulerresponsible for the "shift".For example we can introduce an asynchronous boundary in the
flatMapchain before a certain task, this being literally the implementation of executeAsync:Task.shift.flatMap(_ => task)And this can also be described with
followedByfrom Cats:import cats.syntax.all._ Task.shift.followedBy(task)Or we can specify an asynchronous boundary after the evaluation of a certain task, this being literally the implementation of .asyncBoundary:
task.flatMap(a => Task.shift.map(_ => a))
And again we can also describe this with
forEffectfrom Cats:task.forEffect(Task.shift)
-
def
sleep(timespan: FiniteDuration): Task[Unit]
Creates a new
Taskthat will sleep for the given duration, emitting a tick when that time span is over.Creates a new
Taskthat will sleep for the given duration, emitting a tick when that time span is over.As an example on evaluation this will print "Hello!" after 3 seconds:
import scala.concurrent.duration._ Task.sleep(3.seconds).flatMap { _ => Task.eval(println("Hello!")) }
See Task.delayExecution for this operation described as a method on
Taskreferences or Task.delayResult for the helper that triggers the evaluation of the source on time, but then delays the result. -
def
suspend[A](fa: ⇒ Task[A]): Task[A]
Alias for defer.
-
final
def
synchronized[T0](arg0: ⇒ T0): T0
- Definition Classes
- AnyRef
-
def
tailRecM[A, B](a: A)(f: (A) ⇒ Task[Either[A, B]]): Task[B]
Keeps calling
funtil it returns aRightresult.Keeps calling
funtil it returns aRightresult.Based on Phil Freeman's Stack Safety for Free.
-
def
timer(s: Scheduler): Timer[Task]
Builds a
cats.effect.Timerinstance, given a Scheduler reference.Builds a
cats.effect.Timerinstance, given a Scheduler reference.- Definition Classes
- TaskTimers
-
implicit
val
timer: Timer[Task]
Default, pure, globally visible
cats.effect.Timerimplementation that defers the evaluation toTask's default Scheduler (that's being injected in runAsync)Default, pure, globally visible
cats.effect.Timerimplementation that defers the evaluation toTask's default Scheduler (that's being injected in runAsync)- Definition Classes
- TaskTimers
-
def
toString(): String
- Definition Classes
- AnyRef → Any
-
def
traverse[A, B, M[X] <: TraversableOnce[X]](in: M[A])(f: (A) ⇒ Task[B])(implicit cbf: CanBuildFrom[M[A], B, M[B]]): Task[M[B]]
Given a
TraversableOnce[A]and a functionA => Task[B], sequentially apply the function to each element of the collection and gather their results in the same collection.Given a
TraversableOnce[A]and a functionA => Task[B], sequentially apply the function to each element of the collection and gather their results in the same collection.It's a generalized version of sequence.
-
final
val
unit: Task[Unit]
A
Task[Unit]provided for convenience. -
def
unsafeCreate[A](register: (Context, Callback[A]) ⇒ Unit): Task[A]
Constructs a lazy Task instance whose result will be computed asynchronously.
Constructs a lazy Task instance whose result will be computed asynchronously.
**WARNING:** Unsafe to use directly, only use if you know what you're doing. For building
Taskinstances safely see Task.create.Rules of usage:
- the received
StackedCancelablecan be used to store cancelable references that will be executed upon cancel; everypushmust happen at the beginning, before any execution happens andpopmust happen afterwards when the processing is finished, before signaling the result - the received
FrameRefindicates the current frame index and must be reset on real asynchronous boundaries (which avoids doing extra async boundaries in batched execution mode) - before execution, an asynchronous boundary is recommended, to avoid stack overflow errors, but can happen using the scheduler's facilities for trampolined execution
- on signaling the result (
onSuccess,onError), another async boundary is necessary, but can also happen with the scheduler's facilities for trampolined execution (e.g.asyncOnSuccessandasyncOnError)
**WARNING:** note that not only is this builder unsafe, but also unstable, as the callback type is exposing volatile internal implementation details. This builder is meant to create optimized asynchronous tasks, but for normal usage prefer Task.create.
- the received
-
def
unsafeStartAsync[A](source: Task[A], context: Context, cb: Callback[A]): Unit
Unsafe utility - starts the execution of a Task with a guaranteed asynchronous boundary, by providing the needed Scheduler, StackedCancelable and Callback.
Unsafe utility - starts the execution of a Task with a guaranteed asynchronous boundary, by providing the needed Scheduler, StackedCancelable and Callback.
DO NOT use directly, as it is UNSAFE to use, unless you know what you're doing. Prefer Task.runAsync and .executeAsync.
-
def
unsafeStartNow[A](source: Task[A], context: Context, cb: Callback[A]): Unit
Unsafe utility - starts the execution of a Task, by providing the needed Scheduler, StackedCancelable and Callback.
Unsafe utility - starts the execution of a Task, by providing the needed Scheduler, StackedCancelable and Callback.
DO NOT use directly, as it is UNSAFE to use, unless you know what you're doing. Prefer Task.runAsync.
-
def
unsafeStartTrampolined[A](source: Task[A], context: Context, cb: Callback[A]): Unit
Unsafe utility - starts the execution of a Task with a guaranteed trampolined asynchronous boundary, by providing the needed Scheduler, StackedCancelable and Callback.
Unsafe utility - starts the execution of a Task with a guaranteed trampolined asynchronous boundary, by providing the needed Scheduler, StackedCancelable and Callback.
DO NOT use directly, as it is UNSAFE to use, unless you know what you're doing. Prefer Task.runAsync and .executeAsync.
-
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
- @native() @throws( ... )
-
def
wander[A, B, M[X] <: TraversableOnce[X]](in: M[A])(f: (A) ⇒ Task[B])(implicit cbf: CanBuildFrom[M[A], B, M[B]]): Task[M[B]]
Given a
TraversableOnce[A]and a functionA => Task[B], nondeterministically apply the function to each element of the collection and return a task that will signal a collection of the results once all tasks are finished.Given a
TraversableOnce[A]and a functionA => Task[B], nondeterministically apply the function to each element of the collection and return a task that will signal a collection of the results once all tasks are finished.This function is the nondeterministic analogue of
traverseand should behave identically totraverseso long as there is no interaction between the effects being gathered. However, unliketraverse, which decides on a total order of effects, the effects in awanderare unordered with respect to each other.Although the effects are unordered, we ensure the order of results matches the order of the input sequence. Also see wanderUnordered for the more efficient alternative.
It's a generalized version of gather.
-
def
wanderUnordered[A, B, M[X] <: TraversableOnce[X]](in: M[A])(f: (A) ⇒ Task[B]): Task[List[B]]
Given a
TraversableOnce[A]and a functionA => Task[B], nondeterministically apply the function to each element of the collection without keeping the original ordering of the results.Given a
TraversableOnce[A]and a functionA => Task[B], nondeterministically apply the function to each element of the collection without keeping the original ordering of the results.This function is similar to wander, but neither the effects nor the results will be ordered. Useful when you don't need ordering because:
- it has non-blocking behavior (but not wait-free)
- it can be more efficient (compared with wander), but not necessarily (if you care about performance, then test)
It's a generalized version of gatherUnordered.
- def zip2[A1, A2, R](fa1: Task[A1], fa2: Task[A2]): Task[(A1, A2)]
- def zip3[A1, A2, A3](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3]): Task[(A1, A2, A3)]
- def zip4[A1, A2, A3, A4](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4]): Task[(A1, A2, A3, A4)]
- def zip5[A1, A2, A3, A4, A5](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5]): Task[(A1, A2, A3, A4, A5)]
- def zip6[A1, A2, A3, A4, A5, A6](fa1: Task[A1], fa2: Task[A2], fa3: Task[A3], fa4: Task[A4], fa5: Task[A5], fa6: Task[A6]): Task[(A1, A2, A3, A4, A5, A6)]
- object Context extends Serializable
- object FrameIndexRef
-
object
Par extends Newtype1[Task]
Newtype encoding, see the Task.Par type alias for more details.
Newtype encoding, see the Task.Par type alias for more details.
- Definition Classes
- TaskParallelNewtype
Deprecated Value Members
-
def
fork[A](fa: Task[A], s: Scheduler): Task[A]
DEPRECATED — please use .executeOn.
DEPRECATED — please use .executeOn.
The reason for the deprecation is the repurposing of the word "fork".
- Annotations
- @deprecated
- Deprecated
(Since version 3.0.0) Please use Task!.executeOn
-
def
fork[A](fa: Task[A]): Task[A]
DEPRECATED — please use .executeAsync.
DEPRECATED — please use .executeAsync.
The reason for the deprecation is the repurposing of the word "fork".
- Annotations
- @deprecated
- Deprecated
(Since version 3.0.0) Please use Task!.executeAsync