File

lib/core/src/user-cancel/user-cancel.class.ts

Description

TODO: Needs documentation; also, is this used anywhere?

Extends

Observable

Implements

PromiseLike

Index

Properties
Methods

Constructor

constructor(reason: string)
Parameters :
Name Type Optional
reason string No

Properties

Public canceled
Default value : false
Protected observers
Type : Set<Observer<string>>
Default value : new Set()
Protected promise
Type : Promise<string>
Protected resolvePromise
Type : function
Static UserCanceledError
Default value : UserCanceledError

Methods

cancel
cancel(reason?: string)
Parameters :
Name Type Optional
reason string Yes
Returns : void
then
then(onfulfilled?: | undefined | null, onrejected?: | undefined | null)
Parameters :
Name Type Optional
onfulfilled | undefined | null Yes
onrejected | undefined | null Yes
Returns : PromiseLike<never>
import {	
			Observable,
			Observer,
		}									from 'rxjs'

export class UserCanceledError extends Error {}

/**
 * TODO: Needs documentation; also, is this used anywhere?
 */
export class UserCancel extends Observable<string> implements PromiseLike<void> {


	protected promise			: Promise<string>
	protected resolvePromise	: (str:string) => void
	protected observers			: Set<Observer<string>> = new Set()

	public canceled = false

	static UserCanceledError = UserCanceledError


	constructor(
		protected reason	: string = 'UserCancel: no reason given'
	){

		super( (observer: Observer<string>) => {

			if(this.canceled){

				observer.next(this.reason)
				observer.complete()
				return () => {}

			} else {

				this.observers.add(observer)
				return () => { this.observers.delete(observer) }
			}							

		})

		this.promise		=	new Promise( resolve => this.resolvePromise = resolve )

	}


	then(
		onfulfilled?	: (() => (PromiseLike<never> | never)) | undefined | null,
		onrejected?		: ((reason: any) => never | PromiseLike<never>) | undefined | null,

	): PromiseLike<never> {
		return this.promise.then( () => Promise.reject(new UserCanceledError(this.reason) ) )
	}


	cancel(reason?:string): void {

		this.canceled = true

		this.reason = reason || this.reason

		this.resolvePromise(this.reason)

		this.observers.forEach( observer => {

			observer.next(this.reason)
			observer.complete()
			this.observers.delete(observer)

		})


	}

}

results matching ""

    No results matching ""