Last active
December 13, 2018 19:04
-
-
Save ThomasBurleson/9ebc7d6928a65300e0e50d6b2d784edb to your computer and use it in GitHub Desktop.
Compare switchMap() to nested subscribe calls.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component, OnInit} from '@angular/core'; | |
import {ActivatedRoute} from '@angular/router'; | |
import {ContactsService} from '../contacts.service'; | |
import {Contact} from '../models/contact'; | |
import 'rxjs/add/operator/switchMap'; | |
import {Subscription} from 'rxjs'; | |
@Component({ | |
selector: 'trm-contacts-detail', | |
templateUrl: './contacts-detail.component.html', | |
styleUrls: ['./contacts-detail.component.css'] | |
}) | |
export class ContactsDetailComponent implements OnInit { | |
subscription: Subscription; | |
contact: Contact; | |
constructor(private contactsService: ContactsService, private route: ActivatedRoute) { | |
} | |
/** | |
* BEST WAY! | |
* We need to subscribe to params changes because this component is | |
* reused when jumping between contacts. Hence ngOnInit isn't called | |
*/ | |
ngOnInit() { | |
this.subscription = this.route.params | |
.switchMap(params => this.contactsService.getContact(params['id'])) | |
.subscribe(contact => this.contact = contact); | |
} | |
/** | |
* BAD WAY! | |
* This is the traditional nested approach to chaining async stream events. | |
* Notice the `clean()` function required to unsubscribe on errors and completion. | |
*/ | |
ngOnInit2() { | |
this.subscription = this.route.params.subscribe(params => { | |
let clean = () => restSub.unsubscribe(); | |
let restSub = this.contactsService | |
.getContact(params['id']) | |
.subscribe(contact => { | |
this.contact = contact; | |
clean(); | |
}, clean ); | |
}); | |
} | |
ngOnDestroy() { | |
this.subscription.unsubscribe(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This would be more helpful is you explained why clean is needed, other than that looks great.