The code below creates Observable
that passes current Date
every second.
(下面的代码创建了Observable
,它每秒传递一次当前的Date
。)
From the code below I see that Observable<Date>
is returned from the ObservableService
& subscribed right away in AppComponent
. (从下面的代码中,我看到Observable<Date>
是从ObservableService
返回的,并立即在AppComponent
订阅。)
Although Observable<Date>
was not saved in AppComponent as a class internal variable, the app continues to receive notifications and the returned Observable<Date>
is not collected by the GC. (尽管Observable<Date>
并未作为类内部变量保存在AppComponent中,但该应用程序继续接收通知,并且GC未收集返回的Observable<Date>
。)
My question is why it is so, why Observable<Date>
was not collected/removed when no object is referencing or capturing it?
(我的问题是为什么会这样,为什么没有对象引用或捕获时没有收集/删除Observable<Date>
?)
My main assumption here is that closure in AppComponent
: data => this.currentTime = data
captures this ( AppComponent
) but not vise versa. (我这里的主要假设是AppComponent
中的闭包: data => this.currentTime = data
捕获了此( AppComponent
),反之则不然。)
So as Observable<Date>
is not captured in AppComponent
, Observable<Date>
should be removed soon after creation. (因此,作为Observable<Date>
不在捕捉AppComponent
, Observable<Date>
应创建不久后删除。)
However it does not happen. (但是它不会发生。)
Again, what is the reason for this? (同样,这是什么原因呢?)
observable.service.ts
(observable.service.ts)
import { Observable, interval } from 'rxjs';
export class ObservableService {
createObservableService(): Observable<Date> {
return new Observable(
observer => {
interval(1000)
.subscribe((_) => observer.next(new Date()));
}
);
}
}
app.component.ts
(app.component.ts)
import { Component } from "@angular/core";
import { ObservableService } from "./observable.service";
@Component({
selector: 'app-root',
providers: [ ObservableService ],
template: `<h1>Custom observable service</h1>
Current time: {{currentTime | date: 'mediumTime'}}
`})
export class AppComponent {
currentTime: Date;
constructor(private observableService: ObservableService) {
this.observableService.createObservableService()
.subscribe( data => this.currentTime = data );
}
}
app.module.ts
(app.module.ts)
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ObservableService } from "./observable.service";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [ObservableService],
bootstrap: [AppComponent]
})
export class AppModule { }
ask by Ievgen Gavrysh translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…