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

Scala Cancelable类代码示例

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

本文整理汇总了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 = ???
    }

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


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

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


示例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))
    )
  }
} 
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:53,代码来源:ObservablesPartitioner.scala


示例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)
} 
开发者ID:joesan,项目名称:monix-samples,代码行数:44,代码来源:MyConnectableObservable.scala


示例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
} 
开发者ID:hypertino,项目名称:hyperbus,代码行数:52,代码来源:SubjectSubscription.scala


示例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()
  }
} 
开发者ID:ayoub-benali,项目名称:signal-desktop-client,代码行数:53,代码来源:EventDispatcher.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala EventFilter类代码示例发布时间:2022-05-23
下一篇:
Scala ForeignKeyQuery类代码示例发布时间: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