Do something on unsubscribe

Hi, iam trying to implement service, which handles nfc scanning through reader mode. In this service, i have subject, which is accessible from outside as observable and it emits scanned tags. The problem is, i have to start scan and end nfc scan manually from component too. Is it possible to run some code when someone unsubscribes from observable? For this concrete example i would like to call stopNfcScan function, when someone unsubscribes form getTagSource. Is it possible?

export class NfcService {

  private _tagSource=new Subject();

  constructor() { }

  getTagSource(){
    return this._tagSource.asObservable();
  }

  startNfcScan() {
    nfc.readerMode(nfc.FLAG_READER_NFC_A,(tag)=>{
      console.log(this.transformTag(tag.id));
      this.stopNfcScan();
    },err=>{
      console.log(err);
  });

  }

  stopNfcScan() {
    nfc.disableReaderMode(
      () => console.log("NFC reader mode disabled"),
      error => console.log("Error disabling NFC reader mode", error)
    );
  }

I do this with the using function.

class NfcService {
  private tagSource: Subject<Tag>;
  constructor() {
    tagSource = using(() => {
      return {
        unsubscribe: () => {
          this.stopNfcScan();
        }
      };
    }, () => {
      // could call `startNfcScan` somehow here if desired
      return new Subject<Tag>();
    }).pipe(share());
  }

  // i see no point to using `asObservable`
  getTagSource(): { return this.tagSource; }
}
2 Likes