import { Event, EventLike, EventStream, EventStreamSeed, isEnd, isValue, Observer, Scope, Subscribe, toEvents, Unsub, } from "./abstractions" import { applyScopeMaybe } from "./applyscope" import { EventStreamSeedImpl } from "./eventstream" import { nop } from "./util" export function fromSubscribe(subscribe: Subscribe): EventStreamSeed export function fromSubscribe( subscribe: Subscribe, scope: Scope ): EventStream export function fromSubscribe( subscribe: Subscribe, scope?: Scope ): EventStream | EventStreamSeed { return applyScopeMaybe( new EventStreamSeedImpl("fromSubscribe(fn)", subscribe), scope ) } export type FlexibleObserver = (event: EventLike) => void export type FlexibleSubscribe = (observer: FlexibleObserver) => Unsub export function toFlexibleObserver( onValue: Observer, onEnd: Observer = nop ): FlexibleObserver { return (eventLike: EventLike) => { const events = toEvents(eventLike) for (const event of events) { if (isValue(event)) { onValue(event.value) } else { onEnd() return } } } } export function fromFlexibleSubscibe( subscribe: FlexibleSubscribe ): EventStreamSeed export function fromFlexibleSubscibe( subscribe: FlexibleSubscribe, scope: Scope ): EventStream export function fromFlexibleSubscibe( subscribe: FlexibleSubscribe, scope?: Scope ): EventStream | EventStreamSeed { return applyScopeMaybe( new EventStreamSeedImpl("fromSubscribe(fn)", (onValue, onEnd) => subscribe(toFlexibleObserver(onValue, onEnd)) ), scope ) }