Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

subject进行asObservable转换是否必要 #64

Open
alanhe421 opened this issue Aug 1, 2018 · 0 comments
Open

subject进行asObservable转换是否必要 #64

alanhe421 opened this issue Aug 1, 2018 · 0 comments

Comments

@alanhe421
Copy link
Owner

alanhe421 commented Aug 1, 2018

ng官网在讲组件通讯时,给出了3种方案,第三种是利用rxjs的观察订阅模式。其中有如下代码块

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs';
 
@Injectable()
export class MissionService {
 
  // Observable string sources
  private missionAnnouncedSource = new Subject<string>();
  private missionConfirmedSource = new Subject<string>();
 
  // Observable string streams
  missionAnnounced$ = this.missionAnnouncedSource.asObservable();
  missionConfirmed$ = this.missionConfirmedSource.asObservable();
 
  // Service message commands
  announceMission(mission: string) {
    this.missionAnnouncedSource.next(mission);
  }
 
  confirmMission(astronaut: string) {
    this.missionConfirmedSource.next(astronaut);
  }
}

我们注意到在创建subject对象后利用asObservable进行了转换,查看源码,返回类型为observable。但是要知道subject本身就是一类特殊的observable,兼具observable和observer的性质,本身也可以订阅。
如下这样是可以的。
image

这里的asObservable转换还有必要吗?

看Subject实现细节,我们会明白它多了closed等一些信息,而这些observable是没有的。所以只有当我们需要隐藏内部实现细节,只关心改变的值时,我们就需要这个转换。但是比如我们利用subject了解这个订阅关闭没关闭等,这就需要subject才可以了。
image

其实这个疑问在网上也有类似的讨论,戳这里

alanhe421 pushed a commit that referenced this issue Aug 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant