本文整理汇总了Scala中monix.execution.Cancelable类的典型用法代码示例。如果您正苦于以下问题:Scala Cancelable类的具体用法?Scala Cancelable怎么用?Scala Cancelable使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Cancelable类的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: QQAsyncTestSuite
//设置package包名称以及导入依赖的类
package qq
import java.util.concurrent.TimeUnit
import monix.execution.schedulers.ExecutionModel
import monix.execution.{Cancelable, Scheduler}
import org.scalatest.AsyncFreeSpec
import scala.concurrent.ExecutionContext
abstract class QQAsyncTestSuite extends AsyncFreeSpec with QQTestSuite with AsyncTestUtil {
implicit val schedulerVal: Scheduler = scheduler(super.executionContext)
def scheduler(implicit executionContext: ExecutionContext): Scheduler =
new Scheduler {
override def execute(runnable: Runnable): Unit = executionContext.execute(runnable)
override def reportFailure(t: Throwable): Unit = executionContext.reportFailure(t)
override def scheduleOnce(initialDelay: Long, unit: TimeUnit, r: Runnable): Cancelable = {
executionContext.execute(r)
Cancelable.empty
}
override def scheduleWithFixedDelay(initialDelay: Long, delay: Long, unit: TimeUnit, r: Runnable): Cancelable = {
???
}
override def scheduleAtFixedRate(initialDelay: Long, period: Long, unit: TimeUnit, r: Runnable): Cancelable = {
???
}
override def currentTimeMillis(): Long = System.currentTimeMillis()
override def executionModel: ExecutionModel = ExecutionModel.SynchronousExecution
override def withExecutionModel(em: ExecutionModel): Scheduler = ???
}
}
示例2: 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"))
}
示例3: getObservable
//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.util
import akka.agent.Agent
import monix.execution.{Ack, Cancelable, Scheduler}
import monix.reactive._
import monix.reactive.observables.GroupedObservable
import monix.reactive.observers.Subscriber
import monix.reactive.subjects.PublishSubject
import scala.concurrent.{ExecutionContext, Future}
trait ObservablesPartitioner[K, V] {
def getObservable(key: K): Observable[V]
}
object CachedObservablesPartitioner {
def fromUngroupedObservable[K, InputV, OutputV](
observable: Observable[InputV],
cacheSizePerKey: Int,
keySelector: InputV => K,
mappingFunction: InputV => OutputV
)(implicit scheduler: Scheduler): (CachedObservablesPartitioner[K, InputV, OutputV], Cancelable) = {
val partitioner = new CachedObservablesPartitioner[K, InputV, OutputV](cacheSizePerKey, mappingFunction)
val cancelable = observable.groupBy(keySelector).subscribe(partitioner)
(partitioner, cancelable)
}
}
class CachedObservablesPartitioner[K, InputV, OutputV](
cacheSizePerKey: Int, mappingFunction: InputV => OutputV
)(implicit ec: ExecutionContext)
extends Observer[GroupedObservable[K, InputV]] with ObservablesPartitioner[K, OutputV] {
private val observablesByKey = Agent[Map[K, Observable[OutputV]]](Map.empty)
private val incomingKeys = PublishSubject[K]()
def onComplete(): Unit = {
incomingKeys.onComplete()
}
def onError(e: Throwable): Unit = {
System.err.println(e) // TODO: Better logging?
incomingKeys.onError(e)
}
def getObservable(key: K): Observable[OutputV] = {
observablesByKey.get.getOrElse(
key,
incomingKeys.findF(_ == key).flatMap(_ => getObservable(key))
)
}
}
示例4: MyConnectableObservable
//设置package包名称以及导入依赖的类
package my.samples.observables
import com.typesafe.scalalogging.LazyLogging
import monix.execution.{ Cancelable, Scheduler }
import monix.execution.cancelables.{ BooleanCancelable, SingleAssignmentCancelable }
import monix.reactive.Observable
import monix.reactive.observables.ConnectableObservable
import monix.reactive.observers.Subscriber
import my.samples.services.ZombieConnectorService
import scala.concurrent.duration._
class MyConnectableObservable(service: ZombieConnectorService)(implicit s: Scheduler) extends ConnectableObservable[Long] with LazyLogging {
private[this] val connection = SingleAssignmentCancelable()
private val serviceName = service.getClass.getName
override def connect(): Cancelable = {
logger.info(s"connecting to the service $serviceName")
// 1. we connect to the service first
service.connect()
// 2. we register a callback that says what to do when we disconnect
connection := BooleanCancelable { () =>
service.disconnect()
}
connection
}
def close() = {
logger.info(s"shutting down connection to service $serviceName")
connection.cancel()
}
override def unsafeSubscribeFn(subscriber: Subscriber[Long]): Cancelable =
Observable.interval(1.second).subscribe(subscriber)
}
object MyConnectableObservable {
def apply(service: ZombieConnectorService)(implicit s: Scheduler) =
new MyConnectableObservable(service)
}
示例5: SubjectSubscription
//设置package包名称以及导入依赖的类
package com.hypertino.hyperbus.util
import com.hypertino.hyperbus.transport.api.matchers.RequestMatcher
import monix.eval.Task
import monix.execution.Ack.Stop
import monix.execution.{Ack, Cancelable, Scheduler}
import monix.reactive.{Observable, Observer}
import monix.reactive.observers.Subscriber
import monix.reactive.subjects.{ConcurrentSubject, Subject}
import scala.util.Success
abstract class SubjectSubscription[T](implicit val scheduler: Scheduler) extends FuzzyMatcher {
type eventType = T
// FyzzyIndex properties
def requestMatcher: RequestMatcher
override def indexProperties: Seq[FuzzyIndexItemMetaInfo] = requestMatcher.indexProperties
override def matches(other: Any): Boolean = requestMatcher.matches(other)
// Subject properties
protected val subject: Subject[eventType, eventType]
def cancel(): Unit = {
remove()
subject.onComplete()
}
def publish(t: eventType): Task[Ack] = {
Task.fromFuture(subject.onNext(t).andThen {
case Success(Stop) ? remove()
})
}
private def cancel_1() = cancel()
val observable: Observable[eventType] = new Observable[eventType] {
override def unsafeSubscribeFn(subscriber: Subscriber[eventType]): Cancelable = {
val original: Cancelable = subject.unsafeSubscribeFn(subscriber)
add()
new Cancelable {
override def cancel(): Unit = {
cancel_1()
original.cancel()
}
}
}
}
protected def remove(): Unit
protected def add(): Unit
}
示例6: publishEvent
//设置package包名称以及导入依赖的类
package de.m7w3.signal.events
import de.m7w3.signal.Logging
import monix.execution.Ack.Stop
import monix.execution.Scheduler.Implicits.global
import monix.execution.atomic.{Atomic, AtomicBoolean}
import monix.execution.{Ack, Cancelable}
import monix.reactive.OverflowStrategy.DropOld
import monix.reactive.subjects.ConcurrentSubject
import scala.concurrent.Future
trait EventPublisher {
def publishEvent(event: SignalDesktopEvent): Future[Ack]
}
trait EventDispatcher {
def register(listener: EventListener): Cancelable
}
class SignalDesktopEventDispatcher extends EventPublisher with EventDispatcher with Logging {
private val alive: AtomicBoolean = Atomic(true)
private val bufferSize: Int = 1024
private val overflowStrategy = DropOld(bufferSize)
// ensures concurrency,safety
// and backpressure by maintaining a buffer
// in this subject that sits before any subscriber
// but has the drawback that we might execute stuff asynchronously
private val subject: ConcurrentSubject[SignalDesktopEvent, SignalDesktopEvent] =
ConcurrentSubject.publish[SignalDesktopEvent](overflowStrategy)
override def publishEvent(event: SignalDesktopEvent): Future[Ack] = {
if (alive.get) {
subject.onNext(event)
} else {
logger.warn(s"closed. ignoring event $event")
Stop
}
}
override def register(listener: EventListener): Cancelable = {
subject.subscribe(listener)
}
def close(): Unit = {
alive.set(false)
subject.onComplete()
}
}