import {Observable, shareReplay} from 'rxjs';

/**
 * Create an observable from an intersection observer
 */
export function fromIntersectionObserver(
  target: Element,
  init?: IntersectionObserverInit,
): Observable<IntersectionObserverEntry[]> {
  return new Observable<IntersectionObserverEntry[]>(observer => {
    const intersectionObserver = new IntersectionObserver(item => {
      observer.next(item);
    }, init);
    intersectionObserver.observe(target);

    return {
      unsubscribe() {
        intersectionObserver.disconnect();
      },
    };
  }).pipe(shareReplay(1));
}
