// RUN: %target-swift-frontend -emit-ir %s

// https://github.com/apple/swift/issues/46601

public enum Event<Element, Error: Swift.Error> {
  case next(Element)
  case failed(Error)
  case completed
} 

public typealias Observer<Element, Error: Swift.Error> = (Event<Element, Error>) -> Void

public protocol Disposable { 
  
  func dispose()
  
  var isDisposed: Bool { get }
}

public protocol SignalProtocol {

  /// The type of elements generated by the signal.
  associatedtype Element

  /// The type of error that can terminate the signal.
  associatedtype Error: Swift.Error

  /// Register an observer that will receive events from a signal.
  /// This actually triggers event production. Use the returned disposable
  /// to unsubscribe and cancel event production.
  func observe(with observer: @escaping Observer<Element, Error>) -> Disposable
}


public protocol ObserverProtocol {

  /// Type of elements being received.
  associatedtype Element

  /// Type of error that can be received.
  associatedtype Error: Swift.Error

  /// Send the event to the observer.
  func on(_ event: Event<Element, Error>)
}


/// A type that is both a signal and an observer.
public protocol SubjectProtocol: SignalProtocol, ObserverProtocol {
}


public final class AnySubject<Element, Error: Swift.Error>: SubjectProtocol {
  private let baseObserve: (@escaping Observer<Element, Error>) -> Disposable
  private let baseOn: Observer<Element, Error>


  public init<S: SubjectProtocol>(base: S) where S.Element == Element, S.Error == Error {
    baseObserve = base.observe
    baseOn = base.on
  }

  public func on(_ event: Event<Element, Error>) {
    return baseOn(event)
  }

  public func observe(with observer: @escaping Observer<Element, Error>) -> Disposable {
    return baseObserve(observer)
  }
}
