How to use observable-fns - 10 common examples

To help you get started, we’ve selected a few observable-fns examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github satoshipay / solar / src / workers / net-worker / stellar-network.ts View on Github external
function subscribeToOrderbookUncached(horizonURL: string, sellingAsset: string, buyingAsset: string) {
  const buying = parseAssetID(buyingAsset)
  const selling = parseAssetID(sellingAsset)
  const query = createOrderbookQuery(selling, buying)

  if (selling.equals(buying)) {
    return Observable.from([createEmptyOrderbookRecord(buying, buying)])
  }

  const createURL = () => String(new URL(`/order_book?${qs.stringify({ ...query, cursor: "now" })}`, horizonURL))
  const fetchUpdate = () => fetchOrderbookRecord(horizonURL, sellingAsset, buyingAsset)

  let latestKnownSnapshot = ""

  // TODO: Optimize - Make UpdateT = ValueT & { [$snapshot]: string }

  return subscribeToUpdatesAndPoll({
    async applyUpdate(update) {
      latestKnownSnapshot = JSON.stringify(update)
      return update
    },
    fetchUpdate,
    async init() {
github satoshipay / solar / src / hooks / _caches.ts View on Github external
observe(selector: SelectorT, observe: () => ObservableLike) {
      const cacheKey = createCacheKey(selector)
      const cached = observables.get(cacheKey)

      if (cached) {
        return cached
      } else {
        // Multicast it, so we re-use the existing subscription
        // instead of setting up listeners over and over again
        const multicasted = multicast(observe())
        // TODO: Check if this value is actually newer than the old one
        observables.set(cacheKey, multicasted)
        return multicasted
      }
    }
  }
github andywer / threads.js / test / workers / count-to-five.ts View on Github external
expose(function countToFive() {
  return new Observable(observer => {
    for (let counter = 1; counter <= 5; counter++) {
      observer.next(counter)
    }
    observer.complete()
  })
})
github andywer / threads.js / src / master / spawn.ts View on Github external
function createEventObservable(worker: WorkerType, workerTermination: Promise): Observable {
  return new Observable(observer => {
    const messageHandler = ((messageEvent: MessageEvent) => {
      const workerEvent: WorkerMessageEvent = {
        type: WorkerEventType.message,
        data: messageEvent.data
      }
      observer.next(workerEvent)
    }) as EventListener
    const rejectionHandler = ((errorEvent: PromiseRejectionEvent) => {
      debugThreadUtils("Unhandled promise rejection event in thread:", errorEvent)
      const workerEvent: WorkerInternalErrorEvent = {
        type: WorkerEventType.internalError,
        error: Error(errorEvent.reason)
      }
      observer.next(workerEvent)
    }) as EventListener
    worker.addEventListener("message", messageHandler)
github andywer / threads.js / src / master / invocation-proxy.ts View on Github external
function createObservableForJob(worker: WorkerType, jobUID: number): Observable {
  return new Observable(observer => {
    let asyncType: "observable" | "promise" | undefined

    const messageHandler = ((event: MessageEvent) => {
      debugMessages("Message from worker:", event.data)
      if (!event.data || event.data.uid !== jobUID) return

      if (isJobStartMessage(event.data)) {
        asyncType = event.data.resultType
      } else if (isJobResultMessage(event.data)) {
        if (asyncType === "promise") {
          if (typeof event.data.payload !== "undefined") {
            observer.next(event.data.payload)
          }
          observer.complete()
          worker.removeEventListener("message", messageHandler)
        } else {
github satoshipay / solar / src / workers / _util / subscription.ts View on Github external
export function subscribeToUpdatesAndPoll(
  implementation: SubscriberImplementation,
  options?: { retryFetchOnNoUpdate: boolean }
): Observable {
  const { retryFetchOnNoUpdate = true } = options || {}

  return multicast(
    new Observable(observer => {
      let cancelled = false

      let unsubscribe = () => {
        cancelled = true
      }

      const handleUnexpectedError = (error: Error) => {
        try {
          if (implementation.handleError) {
            implementation.handleError(error)
          } else {
            throw error
          }
        } catch (error) {
          observer.error(error)
        }
github andywer / threads.js / src / master / invocation-proxy.ts View on Github external
return ((...rawArgs: Args) => {
    const uid = nextJobUID++
    const { args, transferables } = prepareArguments(rawArgs)
    const runMessage: MasterJobRunMessage = {
      type: MasterMessageType.run,
      uid,
      method,
      args
    }
    debugMessages("Sending command to run function to worker:", runMessage)
    worker.postMessage(runMessage, transferables)
    return ObservablePromise.from(multicast(createObservableForJob(worker, uid)))
  }) as any as ProxyableFunction
}
github satoshipay / solar / src / workers / _util / subscription.ts View on Github external
export function subscribeToUpdatesAndPoll(
  implementation: SubscriberImplementation,
  options?: { retryFetchOnNoUpdate: boolean }
): Observable {
  const { retryFetchOnNoUpdate = true } = options || {}

  return multicast(
    new Observable(observer => {
      let cancelled = false

      let unsubscribe = () => {
        cancelled = true
      }

      const handleUnexpectedError = (error: Error) => {
        try {
          if (implementation.handleError) {
            implementation.handleError(error)
          } else {
            throw error
          }
        } catch (error) {
          observer.error(error)
github andywer / threads.js / src / master / pool.ts View on Github external
constructor(
    spawnWorker: () => Promise,
    optionsOrSize?: number | PoolOptions
  ) {
    const options: PoolOptions = typeof optionsOrSize === "number"
      ? { size: optionsOrSize }
      : optionsOrSize || {}

    const { size = defaultPoolSize } = options

    this.debug = DebugLogger(`threads:pool:${slugify(options.name || String(nextPoolID++))}`)
    this.options = options
    this.workers = spawnWorkers(spawnWorker, size)

    this.eventObservable = multicast(Observable.from(this.eventSubject))

    Promise.all(this.workers.map(worker => worker.init)).then(
      () => this.eventSubject.next({
        type: PoolEventType.initialized,
        size: this.workers.length
      }),
      error => {
        this.debug("Error while initializing pool worker:", error)
        this.eventSubject.error(error)
        this.initErrors.push(error)
      }
    )
  }
github satoshipay / solar / src / workers / net-worker / stellar-network.ts View on Github external
  }).flatMap((txs: Horizon.TransactionResponse[]) => Observable.from(txs))
}

observable-fns

Light-weight observable implementation and utils written in TypeScript. Based on zen-observable.

MIT
Latest version published 3 years ago

Package Health Score

50 / 100
Full package analysis

Similar packages