Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 44f4c40

Browse files
committed
feat: improve async signal managment and not use service as singleton
1 parent 8416b0c commit 44f4c40

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

front/src/app/features/supports/services/webrtc.service.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ import { SessionService } from "../../../core/services/session.service";
44
import { rxStompConfig } from "../config/rx-stomp.config";
55
import { VisioSignalMessage } from "../interfaces/visio-signal-message";
66
import { SignalingMessageTypeEnum } from "../enums/signaling-message-type.enum";
7-
import { Subject } from "rxjs";
7+
import { from, Subject } from "rxjs";
88

9-
@Injectable({ providedIn: 'root' })
9+
@Injectable()
1010
export class WebrtcService {
1111
private peer!: RTCPeerConnection; // todo: for support multiple peers use an map with the user id for the key.
1212
private localStream!: MediaStream;
@@ -41,10 +41,10 @@ export class WebrtcService {
4141
}
4242

4343
// Close WebRTC connexion
44-
if (this.peer) {
44+
if (this.peer && (this.peer.connectionState === 'connected' || this.peer.connectionState === 'failed')) {
4545
this.peer.close();
46-
this.peer = undefined as any;
4746
}
47+
4848
}
4949

5050
async initPeer(receiverId: number, onRemoteStream: (stream: MediaStream) => void): Promise<void> {
@@ -128,17 +128,21 @@ export class WebrtcService {
128128

129129
case SignalingMessageTypeEnum.ICE:
130130
let candidate: RTCIceCandidate = new RTCIceCandidate(JSON.parse(signal.payload));
131-
if (!this.peer) {
131+
if (this.peerIsNotReady()) {
132132
this.pendingIceCandidates.push(candidate);
133-
return;
133+
break;
134134
}
135135
await this.peer.addIceCandidate(candidate);
136136
break;
137137
}
138138
}
139139

140140
listenToSignals(userId: number): void {
141-
this.rxStomp.watch(`/topic/visio/${userId}`).subscribe((m) => this.handleSignalMessage(m));
141+
this.rxStomp.watch(`/topic/visio/${userId}`).subscribe((msg) => {
142+
from(this.handleSignalMessage(msg)).subscribe({
143+
error: (err) => console.error('Erreur de signal WebRTC:', err)
144+
});
145+
});
142146
}
143147

144148
async setOffer(signal: VisioSignalMessage) {
@@ -156,6 +160,9 @@ export class WebrtcService {
156160
}
157161

158162

163+
peerIsNotReady() : boolean {
164+
return !this.peer || this.peer.connectionState ==='closed';
165+
}
159166

160167
private sendSignal(signal: VisioSignalMessage): void {
161168
this.rxStomp.publish({ destination: '/app/visio.send', body: JSON.stringify(signal) });

0 commit comments

Comments
 (0)