本文整理汇总了Scala中monix.eval.Task类的典型用法代码示例。如果您正苦于以下问题:Scala Task类的具体用法?Scala Task怎么用?Scala Task使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Task类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: RuntimeBench
//设置package包名称以及导入依赖的类
package slate
package bench
import japgolly.scalajs.benchmark.Benchmark.Builder
import japgolly.scalajs.benchmark._
import japgolly.scalajs.benchmark.gui.{GuiParam, GuiParams, GuiSuite}
import monix.eval.Task
import monocle.Iso
import qq.Platform.Rec._
import qq.cc.{CompiledFilter, QQCompiler}
import qq.data.{FilterAST, JSON, QQDSL}
import slate.bench.BenchmarkApp._
object RuntimeBench {
def runtimeSetup(filt: Int => (FilterAST, String)): Builder[(QQRuntimeParams, Int), BenchParams] =
Benchmark.setup[(QQRuntimeParams, Int), BenchParams] {
case (params, size) =>
val (filter, input) = filt(size)
val ready = BenchParams(QQCompiler.compileFilter(Vector.empty, filter).fold(s => sys.error(s.toString), identity), params.iso(input))
ready
}
import japgolly.scalajs.react.vdom.prefix_<^._
@inline final def runRuntimeBench(params: BenchParams): Task[List[JSON]] =
CompiledFilter.run(params.in, Map.empty, params.filt).map(_.getOrElse(???))
val qqRuntimeSuite: GuiSuite[(QQRuntimeParams, Int)] =
GuiSuite.apply[(QQRuntimeParams, Int)](
Suite[(QQRuntimeParams, Int)]("QQ Runtime Benchmarks")(
runtimeSetup(size => (Util.buildRec(QQDSL.compose(_, QQDSL.id), size, QQDSL.id), "[]"))("compose with id")(runRuntimeBench),
runtimeSetup(size => (QQDSL.getPathS(QQDSL.selectKey(s"k$size")), "{" + Stream.tabulate(size)(i => raw""""k$i":"$i"""").mkString(",") + "}"))("select key")(runRuntimeBench),
runtimeSetup(size => (Util.buildRec(QQDSL.add(_, QQDSL.constNumber(1)), size, QQDSL.id), s"$size"))("plus")(runRuntimeBench)
),
GuiParams.two(
Iso.id[(QQRuntimeParams, Int)],
GuiParam.enum[QQRuntimeParams]("Runtime", QQRuntimeParams)(
(p: QQRuntimeParams) => <.span(p.toString()),
initialValues = Seq(QQRuntimeParams)
),
GuiParam.int("Program Size", 1, 5, 10, 20, 50, 100, 200)
)
)
}
示例2: withPrefixes
//设置package包名称以及导入依赖的类
package qq
import cats.~>
import monix.eval.Task
import shapeless.tag._
package object util extends UtilImplicits {
type TaskParallel[A] = Task[A] @@ Parallel
final def withPrefixes[A](xss: List[List[A]], ys: List[A]): List[List[A]] =
for {xs <- xss; y <- ys} yield y :: xs
final def foldWithPrefixes[A](firstPrefix: List[A], nextPrefixes: List[A]*): List[List[A]] =
nextPrefixes.foldLeft(firstPrefix :: Nil)(withPrefixes)
final def withPrefixesV[A](xss: Vector[Vector[A]], ys: Vector[A]): Vector[Vector[A]] =
for {xs <- xss; y <- ys} yield y +: xs
final def foldWithPrefixesV[A](firstPrefix: Vector[A], nextPrefixes: Vector[Vector[A]]): Vector[Vector[A]] =
nextPrefixes.foldLeft(firstPrefix +: Vector.empty)(withPrefixesV)
def single: Option ~> Seq = new (Option ~> Seq) {
def apply[A](op: Option[A]): Seq[A] =
op match {
case None => Vector.empty[A]
case Some(v) => Vector.empty[A] :+ v
}
}
final def unionWithKey[K, A](m1: Map[K, A], m2: Map[K, A])(f: (K, A, A) => A): Map[K, A] = {
val diff = m2 -- m1.keySet
val aug = m1 map {
case (k, v) => if (m2 contains k) k -> f(k, v, m2(k)) else (k, v)
}
aug ++ diff
}
final def unionWith[K, A](m1: Map[K, A], m2: Map[K, A])(f: (A, A) => A): Map[K, A] =
unionWithKey(m1, m2)((_, x, y) => f(x, y))
final def toMapWith[K, V](f: V => K)(seq: Seq[V]): Map[K, V] =
seq.map(v => f(v) -> v)(collection.breakOut)
}
示例3: Runner
//设置package包名称以及导入依赖的类
package qq
package cc
import cats.implicits._
import fastparse.all.{ParseError, Parsed}
import monix.eval.Task
import qq.data.JSON
import qq.util.Recursion.RecursionEngine
// tools for running parts of the compiler together
object Runner {
def parseAndCompile(program: String)(implicit rec: RecursionEngine): (QQCompilationException Either ParseError) Either CompiledFilter = {
Parser.program.parse(program) match {
case Parsed.Success(parsedProgram, _) =>
val optimized = LocalOptimizer.optimizeProgram(parsedProgram)
QQCompiler.compileProgram(Prelude.empty, optimized).leftMap(Either.left)
case f: Parsed.Failure =>
Either.left(Either.right(new ParseError(f)))
}
}
// parse, compile, and run
def run(qqProgram: String)(input: JSON)
(implicit rec: RecursionEngine): (QQCompilationException Either ParseError) Either Task[RuntimeErrs Either Vector[JSON]] = {
parseAndCompile(qqProgram).map(CompiledFilter.run(input, Map.empty, _))
}
}
示例4: apply
//设置package包名称以及导入依赖的类
package qq
package cc
import cats.data.NonEmptyVector
import cats.implicits._
import cats.{Monad, Traverse}
import monix.eval.Task
import org.atnos.eff._
import org.atnos.eff.syntax.all._
import qq.util._
sealed trait FlatTraverseArrs[R, T[_], I, O] extends Any {
def apply(i: I)(implicit ev1: Traverse[T], ev2: Monad[T], ev3: Member[TaskParallel, R]): Eff[R, T[O]] =
suspend(FlatTraverseArrs.run[R, T, I, O](this)(i))
}
case class Encompose[R, T[_], I, O](arrs: NonEmptyVector[FlatTraverseArrs[R, T, Any, Any]]) extends FlatTraverseArrs[R, T, I, O]
case class Leaf[R, T[_], I, O](arr: I => Eff[R, T[O]]) extends AnyVal with FlatTraverseArrs[R, T, I, O]
object FlatTraverseArrs {
def singleton[R, T[_], I, O](arr: I => Eff[R, T[O]]): FlatTraverseArrs[R, T, I, O] =
Leaf[R, T, I, O](arr)
def compose[R, T[_], I, O, O2](first: FlatTraverseArrs[R, T, I, O], second: FlatTraverseArrs[R, T, O, O2]): FlatTraverseArrs[R, T, I, O2] = first match {
case Encompose(arrsFirst) => second match {
case Encompose(arrsSecond) => Encompose[R, T, I, O2](arrsFirst concatNev arrsSecond)
case _: Leaf[R, T, O, O2] => Encompose[R, T, I, O2](NonEmptyVector.fromVectorUnsafe(arrsFirst.toVector.:+[FlatTraverseArrs[R, T, Any, Any], Vector[FlatTraverseArrs[R, T, Any, Any]]](second.asInstanceOf[FlatTraverseArrs[R, T, Any, Any]])))
}
case _: Leaf[R, T, I, O] => second match {
case Encompose(arrsSecond) =>
Encompose[R, T, I, O2](NonEmptyVector.fromVectorUnsafe(arrsSecond.toVector.+:[FlatTraverseArrs[R, T, Any, Any], Vector[FlatTraverseArrs[R, T, Any, Any]]](first.asInstanceOf[FlatTraverseArrs[R, T, Any, Any]])))
case _: Leaf[R, T, O, O2] =>
Encompose[R, T, I, O2](NonEmptyVector.of(first.asInstanceOf[FlatTraverseArrs[R, T, Any, Any]], second.asInstanceOf[FlatTraverseArrs[R, T, Any, Any]]))
}
}
type _taskPar[R] = Member[TaskParallel, R]
def run[R: _taskPar, T[_] : Traverse : Monad, I, O](rt: FlatTraverseArrs[R, T, I, O])(i: I): TaskParallel[Eff[R, T[O]]] = rt match {
case Encompose(rts) =>
rts.reduceLeftTo(rt => (i: Any) => run[R, T, Any, Any](rt)(i))((f, g) =>
(i: Any) =>
Task.now(suspend(f(i)).flatMap(ta => ta.traverseA[R, T[Any]]((a: Any) => suspend(run[R, T, Any, Any](g)(a)))).map(_.flatten)).parallel
)(i).asInstanceOf[Task[Eff[R, T[O]]]].parallel
case Leaf(arr) =>
Task.now(arr(i)).parallel
}
}
示例5: VectorToNelOps
//设置package包名称以及导入依赖的类
package qq
import cats.data._
import monix.eval.Task
import org.atnos.eff.Eff._
import org.atnos.eff._
import qq.cc.FlatTraverseArrs._taskPar
import qq.data.{JSON, VarBinding}
import qq.util._
package object cc {
type VarBindings = Map[String, VarBinding]
type VarEnv[A] = Reader[VarBindings, A]
type RuntimeErrs = NonEmptyList[QQRuntimeError]
type OrRuntimeErr[+A] = Either[RuntimeErrs, A]
type _runtimeErr[R] = Member[Either[RuntimeErrs, ?], R]
type CompiledMathOperator = (JSON, JSON) => Either[RuntimeErrs, JSON]
type CompiledFilterStack = Fx.fx3[VarEnv, TaskParallel, OrRuntimeErr]
type CompiledProgramStack = Fx.fx2[TaskParallel, OrRuntimeErr]
type CompiledFilter = FlatTraverseArrs[CompiledFilterStack, Vector, JSON, JSON]
type OrCompilationError[T] = QQCompilationException Either T
implicit final class VectorToNelOps[A](val l: Vector[A]) extends AnyVal {
@inline def unconsFold[B](b: B, f: (A, Vector[A]) => B): B = if (l.isEmpty) b else f(l.head, l.tail)
@inline def nelFoldLeft1(ifEmpty: A)(foldFun: (A, A) => A): A = if (l.isEmpty) ifEmpty else l.reduceLeft(foldFun)
}
// TODO: remove when added to eff-cats
def suspend[R: _taskPar, A](task: => TaskParallel[Eff[R, A]]): Eff[R, A] =
send[TaskParallel, R, Eff[R, A]](Task.suspend(task).parallel).flatten
}
示例6: identify
//设置package包名称以及导入依赖的类
package slate
import monix.eval.Task
import monix.execution.Cancelable
import slate.chrome._
import scala.scalajs.js
import scala.scalajs.js.UndefOr
object identify {
def chromeCallbackToTask[T](callbackTaker: (T => Unit) => Unit): Task[T] = {
Task.create[T] { (_, callback) =>
callbackTaker { result =>
ChromeRuntime.lastError.fold(callback.onSuccess(result)) { ex =>
callback.onError(ChromeErrorException(ex.message))
}
}
Cancelable.empty
}
}
def getAuthToken(interactive: Boolean = false, accountInfo: UndefOr[String] = js.undefined, scopes: UndefOr[js.Array[String]] = js.undefined): Task[String] =
chromeCallbackToTask(ChromeIdentity.fetchAuthToken(new GetAuthTokenOptions(interactive, accountInfo.map(new AccountInfo(_)), scopes), _))
def launchWebAuthFlow(interactive: Boolean = false, url: String): Task[String] =
chromeCallbackToTask(ChromeIdentity.launchWebAuthFlow(new LaunchWebAuthFlowOptions(url, interactive), _))
def removeCachedAuthToken(token: String): Task[Unit] =
chromeCallbackToTask(ChromeIdentity.removeCachedAuthToken(new RemoveCachedAuthTokenOptions(token), _))
case class ChromeErrorException(message: UndefOr[String]) extends Exception(message.getOrElse("No error message"))
}
示例7: Interact
//设置package包名称以及导入依赖的类
package fakeio
import cats.Id
import monix.eval.Task
import monix.execution.Scheduler
abstract class Interact[F[_]] {
def tell(msg: String): F[Unit]
def ask(prompt: String): F[String]
}
object Interact {
implicit def async(implicit scheduler: Scheduler): Interact[Task] =
new Interact[Task] {
override def tell(msg: String): Task[Unit] = Task(println(msg))
override def ask(prompt: String): Task[String] =
Task {
val result = io.StdIn.readLine(prompt)
println("")
result
}
}
implicit val sync: Interact[Id] =
new Interact[Id] {
override def tell(msg: String): Id[Unit] = println(msg)
override def ask(prompt: String): Id[String] = {
val result = io.StdIn.readLine(prompt)
println("")
result
}
}
def fake(_stdin: List[String]): Interact[FakeIo] =
new Interact[FakeIo] {
private var stdin = _stdin
private var stdout: List[String] = List.empty
override def tell(msg: String): FakeIo[Unit] = {
stdout = msg :: stdout
FakeIo(stdin, stdout, ())
}
override def ask(prompt: String): FakeIo[String] = {
val result = stdin.head
stdin = stdin.tail
stdout = prompt :: stdout
FakeIo(stdin, stdout, result)
}
}
}
示例8: aecorEffectMonixAsyncInstanceForTask
//设置package包名称以及导入依赖的类
package aecor.effect.monix
import aecor.effect.{ Async, Capture, CaptureFuture }
import monix.eval.Task
import scala.concurrent.Future
import scala.util.Try
trait MonixTaskInstances {
implicit def aecorEffectMonixAsyncInstanceForTask(
implicit scheduler: _root_.monix.execution.Scheduler
): Async[_root_.monix.eval.Task] =
new Async[_root_.monix.eval.Task] {
override def unsafeRunCallback[A](fa: Task[A])(f: (Try[A]) => Unit): Unit = {
fa.runOnComplete(f)
()
}
override def unsafeRun[A](fa: _root_.monix.eval.Task[A]): Future[A] = fa.runAsync
}
implicit def aecorEffectMonixCaptureInstanceForTask: Capture[_root_.monix.eval.Task] =
new Capture[_root_.monix.eval.Task] {
override def capture[A](a: => A): _root_.monix.eval.Task[A] = _root_.monix.eval.Task(a)
}
implicit def aecorEffectMonixCaptureFutureInstanceForTask
: CaptureFuture[_root_.monix.eval.Task] =
new CaptureFuture[_root_.monix.eval.Task] {
override def captureFuture[A](future: => Future[A]): _root_.monix.eval.Task[A] =
_root_.monix.eval.Task.deferFuture(future)
}
}
示例9: AccountEndpoint
//设置package包名称以及导入依赖的类
package aecor.example
import aecor.example.MonixSupport._
import aecor.example.domain.account.{ AccountAggregate, AccountId }
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import cats.implicits._
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
import io.circe.generic.JsonCodec
import monix.eval.Task
import AnyValCirceEncoding._
import aecor.example.AccountEndpoint.AccountApiRequest.OpenAccountRequest
class AccountEndpoint(account: AccountAggregate[Task]) {
def openAccount(accountId: AccountId): Task[String Either Unit] =
account
.openAccount(accountId)
.map(_.leftMap(_.toString))
}
object AccountEndpoint {
sealed abstract class AccountApiRequest
object AccountApiRequest {
@JsonCodec final case class OpenAccountRequest(accountId: AccountId) extends AccountApiRequest
}
def route(api: AccountEndpoint): Route =
pathPrefix("account") {
post {
(path("open") & entity(as[AccountApiRequest.OpenAccountRequest])) {
case OpenAccountRequest(accountId) =>
complete {
api.openAccount(accountId).map {
case Left(e) => StatusCodes.BadRequest -> e.toString
case Right(result) => StatusCodes.OK -> ""
}
}
}
}
}
}
示例10: taskToResponseMarshallable
//设置package包名称以及导入依赖的类
package aecor.example
import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshallable, ToResponseMarshaller }
import monix.eval.Task
import monix.execution.Scheduler
trait MonixSupport {
implicit def taskToResponseMarshallable[A](
task: Task[A]
)(implicit A: ToResponseMarshaller[A]): ToResponseMarshallable =
new ToResponseMarshallable {
override implicit def marshaller: ToResponseMarshaller[Task[A]] =
Marshaller { implicit ec => task =>
task.runAsync(Scheduler(ec)).flatMap(A(_))
}
override def value: Task[A] = task
override type T = Task[A]
}
}
object MonixSupport extends MonixSupport
示例11: AccountRepoMutableInterpreter
//设置package包名称以及导入依赖的类
package deaktator.cats.free.ex1.free
import cats.~>
import deaktator.cats.free.ex1.support.Account
import monix.eval.Task
import monix.cats.monixToCatsMonad
import scala.collection.{mutable => scm}
case class AccountRepoMutableInterpreter() extends (AccountRepo ~> Task) {
private[this] val table: scm.Map[String, Account] = scm.Map.empty[String, Account]
// Notice the casting below. This doesn't occur in the finally tagless approach.
// It seems as though this may be an unfortunate necessity.
private[this] val step = new (AccountRepoA ~> Task) {
override def apply[A](action: AccountRepoA[A]): Task[A] = action match {
case Query(no) =>
table.get(no)
.map { a => Task.pure(a).asInstanceOf[Task[A]] }
.getOrElse { throw new RuntimeException(s"Account no $no not found") }
case Store(account) => Task.pure[Unit](table += account.no -> account).asInstanceOf[Task[A]]
case Delete(no) => Task.pure[Unit](table -= no).asInstanceOf[Task[A]]
}
}
def mutableState: Map[String, Account] = table.toMap
override def apply[A](action: AccountRepo[A]): Task[A] = action.foldMap(step)
}
示例12: OwnerController
//设置package包名称以及导入依赖的类
package com.trainologic.samples.petclinic.web
import monix.eval.Task
import cats.~>
import argonaut._
import org.atnos.eff._
import syntax.eff._
import ReaderEffect._
import monix.TaskEffect._
import org.http4s._, org.http4s.dsl._
import argonaut._
import com.trainologic.samples.petclinic._
import service.ClinicService
import repository.OwnerRepository
import model.Owner
import cats.data.Xor
import cats.data.Reader
import model.ArgonautCodecs._
import com.trainologic.samples.petclinic.repository.PetRepository
import com.trainologic.samples.petclinic.model.PetType
class OwnerController[M[_]] {
object LastNameQueryParamMatcher extends QueryParamDecoderMatcher[String]("lastName")
type BaseOwnerStack = Fx.fx4[DataAccessException Xor ?, Validate[String, ?], Reader[ClinicService[M], ?], Reader[OwnerRepository[M], ?]]
type BasePetStack = Fx.fx4[DataAccessException Xor ?, Validate[String, ?], Reader[ClinicService[M], ?], Reader[PetRepository[M], ?]]
//type S1 = FxAppend[Fx1[M], BaseStack]
type S2 = FxAppend[Fx1[Task], BaseOwnerStack]
type S3 = FxAppend[Fx1[Task], BasePetStack]
implicit def ownersEncoder: EntityEncoder[Seq[Owner]] = jsonEncoderOf[Seq[Owner]]
implicit def petTypesEncoder: EntityEncoder[Seq[PetType]] = jsonEncoderOf[Seq[PetType]]
def populatePetTypes(implicit ev: M ~> Task): PartialFunction[Request, Eff[S3, Response]] = {
case request @ GET -> Root / "petTypes" => for {
service <- ask[S3, ClinicService[M]].into
petTypes <- service.findPetTypes.transform(ev).into[S3]
r <- async[S3, Response](Ok(petTypes).unsafePerformSync)
} yield r
}
def processFindForm(implicit ev: M ~> Task): PartialFunction[Request, Eff[S2, Response]] = {
case request @ GET -> Root / "owners" :? LastNameQueryParamMatcher(lastName) => for {
service <- ask[S2, ClinicService[M]].into
owners <- service.findOwnerByLastName(lastName).transform(ev).into[S2]
r <- async[S2, Response](Ok(owners).unsafePerformSync)
} yield r
}
}
示例13: TaglessMonixApp
//设置package包名称以及导入依赖的类
import cats.Monad
import monix.eval.Task
import services.tagless._
class TaglessMonixApp {
def program[F[_]: Monad](
implicit
A: InteractionService[F],
D: DataOpService[F],
L: LogService[F]
): F[String] = {
import A._, D._, L._
import cats.syntax.functor._
import cats.syntax.flatMap._
for {
response <- get("First ?")
_ <- D.add(response)
_ <- L.add(s"Log: Recorded: $response")
response <- get("Second ?")
_ <- D.add(response)
_ <- L.add(s"Log: Recorded: $response")
responses <- findAll()
_ <- print(responses.toString)
_ <- L.add(s"Log: Printed: $responses")
logs <- show()
} yield logs.mkString("\n")
}
def run(in: () => String): Task[String] = {
import monix.cats._
implicit val a = new InteractionInterpreter(in)
implicit val d = new InMemoryDataOpInterpreter()
implicit val l = new LogInterpreter()
program[Task]
}
}
示例14: FreeMonixApp
//设置package包名称以及导入依赖的类
import cats._
import cats.data._
import cats.free._
import monix.cats._
import monix.eval.Task
import services.free._
class FreeMonixApp {
protected type RecordedActionsApp[A] = Coproduct[DataOps.DSL, Interactions.DSL, A]
protected type AuditedRecordedActionsApp[A] = Coproduct[Logs.DSL, RecordedActionsApp, A]
private def program(implicit
A: InteractionService[AuditedRecordedActionsApp],
D: DataOpService[AuditedRecordedActionsApp],
L: LogService[AuditedRecordedActionsApp]
): Free[AuditedRecordedActionsApp, String] = {
import A._, D._, L._
for {
response <- get("First ?")
_ <- D.add(response)
_ <- L.add(s"Log: Recorded: $response")
response <- get("Second ?")
_ <- D.add(response)
_ <- L.add(s"Log: Recorded: $response")
responses <- findAll
_ <- print(responses.toString)
_ <- L.add(s"Log: Printed: $responses")
logs <- show
} yield logs.mkString("\n")
}
protected def interpreter(in: () => String): AuditedRecordedActionsApp ~> Task = {
val recordedActionsInterpreter: RecordedActionsApp ~> Task =
new InMemoryDataOpInterpreter or new InteractionInterpreter(in)
new LogInterpreter or recordedActionsInterpreter
}
def run(in: () => String): Task[String] = {
program.foldMap(interpreter(in))
}
}
示例15: DataOps
//设置package包名称以及导入依赖的类
package services.free
import cats.free.{Free, Inject}
import cats.~>
import monix.eval.Task
object DataOps {
sealed trait DSL[A]
final case class Add(value: String) extends DSL[Option[String]]
final case class FindAll() extends DSL[List[String]]
}
final class DataOpService[F[_]](implicit I: Inject[DataOps.DSL, F]) {
import DataOps._
def add(value: String): Free[F, Option[String]] = Free.inject[DSL, F](Add(value))
def findAll: Free[F, List[String]] = Free.inject[DSL, F](FindAll())
}
object DataOpService {
implicit def dataOps[F[_]](implicit I: Inject[DataOps.DSL, F]): DataOpService[F] = new DataOpService[F]
}
final class InMemoryDataOpInterpreter extends (DataOps.DSL ~> Task) {
import DataOps._
private[this] val storage = new scala.collection.mutable.HashSet[String]
def apply[A](d: DSL[A]) = d match {
case Add(a) => Task { if (storage.add(a)) Some(a) else None }
case FindAll() => Task { storage.toList.sorted }
}
}