0
votes

I have subscribed to a ReplaySubject and trying to unsubscribe in ngOnDestroy method. When I move away from the subscription component and come back to same component wihtout emitting the data, again its getting subscribed. May I know how can I solve this issue?

Shared.service.ts

import { Injectable } from '@angular/core';
import { TestCase } from './test-case-form/test-case.model';
import { Subject } from 'rxjs/Subject';
import { ReplaySubject } from 'rxjs/ReplaySubject';


@Injectable({
providedIn: 'root'
})
export class SharedService {
testCasesChanged = new Subject<TestCase[]>();
private startedEditing = new ReplaySubject<number>();
public startedEditing$ = this.startedEditing.asObservable();

setData(index) {
console.log("setData called", index);
this.startedEditing.next(index);
}
}

a.component.ts

export class TestFormComponent implements OnInit, OnDestroy {
@ViewChild('f') testForm : NgForm;
subscription: Subscription;
editIndex: number;
editMode = false;
editedTestCase: TestCase;

private testCases: TestCase[]= [];

ngOnInit() {
this.subscription = this.sharedService.startedEditing$
.subscribe((index: number) => {
console.log("Subscribed");
this.editIndex = index;
this.editMode = true;
this.editedTestCase = 
this.sharedService.getTestCase(this.editIndex);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
2
Do you mean you're not getting the values of startedEditing during the second time?Caramiriel
it is getting the old values?Fateh Mohamed
Yes it's getting old valueMd Owais
Second time I am loading the component without emitting the value, but it's getting subscribedMd Owais

2 Answers

0
votes

Your unsubscribe in ngOnDestroy works.

You're getting the old values in your component, because you're using a ReplaySubject. A ReplaySubject caches all values, which are emitted with it. So every time you subscribe to that subject your subscribe method is called for every value you have emitted over this ReplaySubject.

It is possible to change the buffer size with:

// Only the last emitted value is cached and emitted to every new subscriptions
private startedEditing = new ReplaySubject<number>(1); 

If you only want to get the last emitted value you can also use a BehaviourSubject.

But I guess you just want to use a simple Subject.

0
votes
private startedEditing = new ReplaySubject<number>();

public startedEditing$ = this.startedEditing.asObservable(); 
// `startedEditing$` is no longer `startedEditing` they are now two different things

then you do

this.startedEditing.next(index);

Which updates only startedEditing

startedEditing$ is never updated in the code you provide. Can you simplify and only use one?