Angular 6 : Auto unsubscribe from RxJS Observeable

Pramoth Suwanpech
Sep 2, 2018 · 1 min read

จากการที่ได้อ่านบทความที่ใช้เทคนิคการ auto unsubscribe ของ RxJS จาก https://angular-guru.com/blog/angular-more-unknown-features โดยใช้ takeUntil operator ตามโค๊ดด้านล่างนี้

มันดีมาก แต่ยังพบว่ายังมี noise อีกนิดหน่อย คือ

  1. ต้อง maintain instance variable _onDetroy ในทุกๆ component ที่เราใช้
  2. ใน onDestroy จะต้องเรียก next() และ complete() ตามลำดับ

ซึ่งเมื่อดูแล้ว เราพอจะมีทางที่เราจะลด noise ตรงนี้ได้ จึงคิดจะทำ operator ที่มันสามารถ auto unsubscribe โดย ที่มันไม่ทำให้เกิด noise สองข้อด้านบน
แต่ก่อนจะเริ่มทำ ได้ค้น google พบว่ามีคนทำไว้แล้ว (https://github.com/NetanelBasal/ngx-take-until-destroy) แต่ว่ามีข้อยังมีข้อจำกัด ที่เรายังไม่ค่อยโอเค คือ

  1. ไม่ typesafe (component ไม่จำเป็นต้อง implement OnDestroy แต่ ต้องการ ngOndetroy() เพราะว่า ถ้าไม่มี ng compiler จะ remove code ออกไป ดังนั้นอาจจะเกิดข้อผิดพลาดจากการไม่ได้ overide ngOnDestroy() ได้)
  2. ไม่รองรับการใช้งานมากกว่า 1 ครั้งใน component เดียวกัน

ดังนั้นจึงได้ติดสินใจทำมาใช้ใหม่ ที่
https://github.com/pramoth/gt-unsubscribe-on-detroy

ติดตั้งโดย npm install — save gt-unsubscribe-on-detroy

ตัวอย่างการใช้งาน

จะพบว่า noise หายไปหมดเลย !! ใครสนใจก็เอาไปใช้ได้เลยนะครับ หรือจะเอาไปปรับปรุงตรงไหนก็ตามสบายเลยครับ
ปล. ใช้กับ RxJS 6/Angular 6 นะครับ มีตัวอย่างการใช้งานใน folder example

    Pramoth Suwanpech

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade