I have a simple app in which users will end up sending messages (very much like a chat-app). I'm starting to implement RxJS to share state between components through a service:
// session.service.ts
export class SessionService {
private subject = new Subject<sessionType.Session>();
constructor() { }
public setSession(session: sessionType.Session) {
this.subject.next(session)
}
public getSession(): Observable<sessionType.Session> {
return this.subject.asObservable()
}
}
// join-session.component.ts
public joinSession(code: FormControl) {
...
this.getSessionSubscription = this.sessionQuery.valueChanges.subscribe(({data}) => {
this.sessionService.setSession(data.getSession)
})
}
// app.component.ts
public sessions: Array<sessionType.Session> = []
public session: sessionType.Session | undefined;
private subscription!: Subscription;
constructor(
private apollo: Apollo,
private sessionService: SessionService
) {
this.subscription = this.sessionService.getSession().subscribe({
next: (session) => this.session = session,
error: (error) => console.log(error),
complete: () => console.log('complete')
})
}
This is all working as expected, when a user joins a session I can see the joined session in the app.component
but I'm not very confident that this is the correct approach. I was hoping someone could either point out what I could improve, or perhaps acknowledged that this is indeed correct.