import { checkFunction } from "../_check" import { Source } from "../_core" import { In, Out, Projection } from "../_interfaces" import { toObs } from "../_interrop" import { makeObservable } from "../_obs" import { Transaction } from "../_tx" import { curry2 } from "../_util" import { dispatcherOf, Observable } from "../Observable" import { once } from "../sources/single" import { Operator } from "./_base" import { flatMap, InnerResult } from "./flatMap" export const flatMapError: CurriedFlatMapError = curry2(_flatMapError) export interface CurriedFlatMapError { ( project: Projection>, observable: In, ): Out (project: Projection>): ( observable: In, ) => Out } function _flatMapError( project: Projection>, observable: Observable, ): Observable { checkFunction(project) return flatMap>, M, T>( unpack, makeObservable(observable, new MapM(dispatcherOf(observable), project)), ) } class MapM extends Operator> { constructor(source: Source, private p: Projection>) { super(source) } public next(tx: Transaction, val: T): void { this.sink.next(tx, new ValM(val)) } public error(tx: Transaction, err: Error): void { this.sink.next(tx, new ErrM(err, this.p)) } } interface M { of(): Observable } class ValM implements M { constructor(private v: T) {} public of(): Observable { return once(this.v) } } class ErrM implements M { constructor(private e: Error, private p: Projection>) {} public of(): Observable { const { e, p } = this return toObs(p(e)) } } function unpack(m: M): Observable { return m.of() }