• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Task类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中monix.eval.Task的典型用法代码示例。如果您正苦于以下问题:Scala Task类的具体用法?Scala Task怎么用?Scala Task使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Task类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
      )
    )

} 
开发者ID:edmundnoble,项目名称:slate,代码行数:47,代码来源:RuntimeBench.scala


示例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)

} 
开发者ID:edmundnoble,项目名称:slate,代码行数:45,代码来源:package.scala


示例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, _))
  }

} 
开发者ID:edmundnoble,项目名称:slate,代码行数:30,代码来源:Runner.scala


示例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
  }

} 
开发者ID:edmundnoble,项目名称:slate,代码行数:52,代码来源:FlatTraverseArrs.scala


示例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

} 
开发者ID:edmundnoble,项目名称:slate,代码行数:36,代码来源:package.scala


示例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"))

} 
开发者ID:edmundnoble,项目名称:slate,代码行数:35,代码来源:identify.scala


示例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)
      }
    }
} 
开发者ID:yawaramin,项目名称:fake-io,代码行数:55,代码来源:Interact.scala


示例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)

    }
} 
开发者ID:notxcain,项目名称:aecor,代码行数:36,代码来源:MonixTaskInstances.scala


示例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 -> ""
              }
            }
        }
      }
    }
} 
开发者ID:notxcain,项目名称:aecor,代码行数:45,代码来源:AccountEndpoint.scala


示例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 
开发者ID:notxcain,项目名称:aecor,代码行数:23,代码来源:MonixSupport.scala


示例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)
} 
开发者ID:deaktator,项目名称:learn-cats,代码行数:31,代码来源:AccountRepoMutableInterpreter.scala


示例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

  }

} 
开发者ID:Trainologic,项目名称:petclinic_eff,代码行数:53,代码来源:OwnerController.scala


示例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]
  }
} 
开发者ID:radusw,项目名称:tagless-free-monix-sample,代码行数:42,代码来源:TaglessMonixApp.scala


示例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))
  }
} 
开发者ID:radusw,项目名称:tagless-free-monix-sample,代码行数:43,代码来源:FreeMonixApp.scala


示例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 }
  }
} 
开发者ID:radusw,项目名称:tagless-free-monix-sample,代码行数:33,代码来源:DataOpService.scala


示例16: Logs

//设置package包名称以及导入依赖的类
package services.free

import cats.free.{Free, Inject}
import cats.~>
import monix.eval.Task

object Logs {
  sealed trait DSL[A]
  final case class Add(a: String) extends DSL[Unit]
  final case class Show() extends DSL[List[String]]
}

final class LogService[F[_]](implicit I: Inject[Logs.DSL, F]) {
  import Logs._
  def add(a: String): Free[F, Unit] = Free.inject[DSL, F](Add(a))
  def show: Free[F, List[String]] = Free.inject[DSL, F](Show())
}
object LogService {
  implicit def logs[F[_]](implicit I: Inject[Logs.DSL, F]): LogService[F] = new LogService[F]
}


final class LogInterpreter extends (Logs.DSL ~> Task) {
  import Logs._

  private[this] val storage = new scala.collection.mutable.ListBuffer[String]

  def apply[A](l: DSL[A]) = l match {
    case Add(a) => Task { storage.append(a) }
    case Show() => Task { storage.toList }
  }
} 
开发者ID:radusw,项目名称:tagless-free-monix-sample,代码行数:33,代码来源:LogService.scala


示例17: Interactions

//设置package包名称以及导入依赖的类
package services.free

import cats.free.{Free, Inject}
import cats.~>
import monix.eval.Task

object Interactions {
  sealed trait DSL[A]
  final case class Get(input: String) extends DSL[String]
  final case class Print(msg: String) extends DSL[Unit]
}

final class InteractionService[F[_]](implicit I: Inject[Interactions.DSL, F]) {
  import Interactions._
  def get(input: String): Free[F, String] = Free.inject[DSL, F](Get(input))
  def print(msg: String): Free[F, Unit] = Free.inject[DSL, F](Print(msg))
}
object InteractionService {
  implicit def actions[F[_]](implicit I: Inject[Interactions.DSL, F]): InteractionService[F] = new InteractionService[F]
}


final class InteractionInterpreter(read: () => String) extends (Interactions.DSL ~> Task) {
  import Interactions._
  def apply[A](a: DSL[A]) = a match {
    case Get(input) => Task { println(input); read() }
    case Print(msg) => Task { println(msg) }
  }
} 
开发者ID:radusw,项目名称:tagless-free-monix-sample,代码行数:30,代码来源:InteractionService.scala


示例18: add

//设置package包名称以及导入依赖的类
package services.tagless

trait DataOpService[F[_]] {
  def add(value: String): F[Option[String]]
  def findAll(): F[List[String]]
}


import monix.eval.Task

final class InMemoryDataOpInterpreter extends DataOpService[Task] {
  private[this] val storage = new scala.collection.mutable.HashSet[String]

  override def add(value: String) = Task {
    if (storage.add(value))
      Some(value)
    else
      None
  }
  override def findAll() = Task(storage.toList.sorted)
} 
开发者ID:radusw,项目名称:tagless-free-monix-sample,代码行数:22,代码来源:DataOpService.scala


示例19: get

//设置package包名称以及导入依赖的类
package services.tagless

trait InteractionService[F[_]] {
  sealed trait DSL[A]
  def get(input: String): F[String]
  def print(msg: String): F[Unit]
}


import monix.eval.Task

final class InteractionInterpreter(read: () => String) extends InteractionService[Task] {
  override def get(input: String) = Task {
    println(input)
    read()
  }
  override def print(msg: String) = Task(println(msg))
} 
开发者ID:radusw,项目名称:tagless-free-monix-sample,代码行数:19,代码来源:InteractionService.scala


示例20: FreeMonixAppSpec

//设置package包名称以及导入依赖的类
import cats.~>
import monix.cats._
import monix.eval.Task
import monix.execution.atomic.Atomic

import scala.concurrent.Await
import scala.concurrent.duration._
import org.specs2.ScalaCheck
import org.specs2.mutable.Specification
import services.free.{InMemoryDataOpInterpreter, InteractionInterpreter, Logs}

class FreeMonixAppSpec extends Specification with ScalaCheck {
  implicit val ctx = monix.execution.Scheduler.Implicits.global

  "FreeMonixApp" should {

    val app = new FreeMonixApp()
    "run" in prop { (a: String, b: String) =>
      val aSent = Atomic(false)
      def in(): String = {
        if (aSent.compareAndSet(expect = false, update = true)) a
        else b
      }

      val result = Await.result(app.run(in).runAsync, 1.seconds)
      val expected = s"Log: Recorded: $a\nLog: Recorded: $b\nLog: Printed: ${Set(a,b).toList.sorted}"
      result == expected
    }.set(maxSize = 16)


    val app2 = new FreeMonixApp {
      private class LogInterpreter2 extends (Logs.DSL ~> Task) {
        import Logs._
        private[this] val storage = new scala.collection.mutable.ListBuffer[String]
        def apply[A](l: DSL[A]) = l match {
          case Add(log) => Task { storage.append(log) }
          case Show() => Task { storage.toList.map(_.toUpperCase.drop(5)) }
        }
      }
      override def interpreter(in: () => String) = {
        new LogInterpreter2().or(new InMemoryDataOpInterpreter().or(new InteractionInterpreter(in)): RecordedActionsApp ~> Task)
      }
    }

    "be able to use other interpreters" in prop { (a: String, b: String) =>
      val aSent = Atomic(false)
      def in(): String = {
        if (aSent.compareAndSet(expect = false, update = true)) a
        else b
      }

      val result = Await.result(app2.run(in).runAsync, 1.seconds)
      val expected = s"RECORDED: ${a.toUpperCase()}\nRECORDED: ${b.toUpperCase}\nPRINTED: ${Set(a,b).toList.sorted.toString().toUpperCase}"
      result == expected
    }.set(maxSize = 16)

  }
} 
开发者ID:radusw,项目名称:tagless-free-monix-sample,代码行数:59,代码来源:FreeMonixAppSpec.scala



注:本文中的monix.eval.Task类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala GenMap类代码示例发布时间:2022-05-23
下一篇:
Scala EofCh类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap