import {take, takeUntil} from "rxjs/operators";
import {OnDestroy, OnInit} from "@angular/core";
import {Observable, Subject} from "rxjs";

export abstract class SubscribingComponent implements OnInit, OnDestroy {
  protected subscribers$ = []
  protected destroy$ = new Subject<boolean>()

  subscribe<T>(observable: Observable<T>, observer, take_count = -1) {
    if (!observer.error) {
      observer.error = err => console.log(err)
    }

    if (take_count >= 0) {
      observable.pipe(take(take_count), takeUntil(this.destroy$))
    } else {
      observable.pipe(takeUntil(this.destroy$))
    }
    this.subscribers$.push(observable.subscribe(observer))
  }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    this.destroy$.next(true)
    this.destroy$.complete()
  }
}
