我遇到需要在函数中放置订阅的情况,该函数被多次调用。
我的问题是,如果我将该功能调用3次,我是否会创建3个新订阅或原始订阅是否会被覆盖?
这个问题背后的原因是我想避免创建多个订阅,以免造成内存泄漏。
var observable = Rx.Observable;
var subscription = new Rx.Subscription();
var numbers = observable.from([1,2,3,4,5,6]);
function foo(){
subscription = numbers.subscribe( val => console.log("numbers subscribes",val) )
subscription.unsubscribe();
}
foo();
foo();
foo();
更新
我被要求显示项目中的实际代码。我遗漏了很多简单的代码,但引用了:
this.messages
请参阅发出数组的observable。
我想安全删除此行:
this.subscriptionPostMessages.unsubscribe();
以下是代码:
import { Injectable, OnDestroy } from '@angular/core';
import { Subject, Observable, Subscription } from 'rxjs';
import { HttpClient, HttpHeaders, HttpEventType, HttpRequest, HttpErrorResponse, HttpEvent, HttpParams } from '@angular/common/http';
import { Message } from '../message/message.model';
import { GlobalsService } from '../globals/globals.service';
import { environment } from '../../environments/environment';
@Injectable()
export class MessagesService implements OnDestroy {
messages: Observable<Message[]>;
postMessages: Observable<Message[]>;
subscriptionPostMessages: Subscription;
constructor(public http: HttpClient,
public globalsService: GlobalsService) {
postMessage(message: Message): void {
const body = {
messageid: message.id,
filename: ''
};
const requestHeaders = new HttpHeaders().set('Content-Type', 'application/json');
const headers = {
headers: requestHeaders
};
this.http.post(this.globalsService.baseUrl + environment.ajax_dir + '/ajax-ng-post-message-module.cfm', body, headers).map(
(res: Response) => {
if('filename' in res && res['filename'] !== ''){
this.postMessages = this.addFileNameToMessage(res['messageid'], res['filename']);
this.subscriptionPostMessages = this.postMessages.subscribe( (messages: Message[]) => {
});
this.subscriptionPostMessages.unsubscribe();
}
return res;
})
.subscribe();
}
addFileNameToMessage(id: string, filename: string): Observable<Message[]> {
return this.messages.map( (messages: Message[]) => {
messages.map( (message: Message) => {
if(message.id === id){
message.file.filename = filename;
message.file.value = '';
}
})
return messages;
})
}
ngOnDestroy() {
if (this.subscriptionPostMessages) {
this.subscriptionPostMessages.unsubscribe();
}
}
}
的作用:
this.subscriptionPostMessages
每次都被覆盖:
postMessage()
被调用?
换句话说,我一次只会有一个订阅活动吗?
答案 0 :(得分:1)
如果您按照提供的方式调用代码,则由于subscribe
和unsubscribe
在同一个函数调用中,因此不会有多个订阅。请注意,考虑到RxJ的异步特性,这将导致您在订阅的onNext
回调中收到的值的意外行为。
我觉得你几乎绊倒了rx-antipattern,但是你需要提供更多关于你想要什么的信息,以便给你一个更好的答案。