본문 바로가기

개발 공부/Angular

RxJS의 ReplaySubject 2 / Angular

상태 관리에 ReplaySubject 활용하기

ReplaySubject는 애플리케이션 상태를 관리하는 데 매우 유용합니다.

새로운 구독자가 초기 상태를 쉽게 가져오고, 상태 변화에 실시간으로 반응할 수 있도록 합니다.

 

import { ReplaySubject } from 'rxjs';

interface AppState {
  user: string | null;
  theme: 'light' | 'dark';
}

const initialState: AppState = {
  user: null,
  theme: 'light',
};

const state$ = new ReplaySubject<AppState>(1);

// 초기 상태 설정
state$.next(initialState);

// 상태 업데이트 함수
function updateState(partialState: Partial<AppState>) {
  state$.subscribe((currentState) => {
    state$.next({ ...currentState, ...partialState });
  });
}

// 상태 구독
state$.subscribe((state) => {
  console.log('Current State:', state);
});

// 상태 변경
updateState({ user: 'JohnDoe' });
updateState({ theme: 'dark' });



//
Current State: { user: null, theme: 'light' }
Current State: { user: 'JohnDoe', theme: 'light' }
Current State: { user: 'JohnDoe', theme: 'dark' }
  • 이 코드는 ReplaySubject를 활용하여 상태를 관리하고, 새로운 구독자가 초기 상태를 받을 수 있도록 설정한 예입니다.

 

컴포넌트 간 데이터 공유

ReplaySubject는 Angular, React와 같은 프레임워크에서 컴포넌트 간 데이터를 쉽게 공유할 수 있게 해줍니다.

import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SharedService {
  private message$ = new ReplaySubject<string>(1);

  sendMessage(message: string) {
    this.message$.next(message);
  }

  getMessage() {
    return this.message$.asObservable();
  }
}


// Component A
this.sharedService.sendMessage('Hello from Component A');

// Component B
this.sharedService.getMessage().subscribe((message) => {
  console.log(message); // Hello from Component A
});
  • 이 예제는 ReplaySubject를 사용하여 Angular의 서비스로 컴포넌트 간 데이터를 공유하는 방법을 보여줍니다. 
  • 새로운 컴포넌트가 구독하면 마지막으로 발행된 메시지를 즉시 받을 수 있습니다.

 

 

고급 옵션 활용

1. 버퍼 크기와 타임 윈도우 조합

ReplaySubject는 버퍼 크기와 타임 윈도우를 조합하여 메모리 효율성과 데이터 유지 정책을 균형 있게 설정할 수 있습니다.

const replaySubject = new ReplaySubject<number>(2, 1000); // 최근 2개의 값, 1초 동안 유지

setInterval(() => {
  const value = Math.floor(Math.random() * 100);
  console.log('Generated:', value);
  replaySubject.next(value);
}, 500);

setTimeout(() => {
  replaySubject.subscribe((value) => {
    console.log('Subscriber received:', value);
  });
}, 2000);



//출력 결과
Generated: 42
Generated: 23
Generated: 87
Subscriber received: 87
Generated: 55
Subscriber received: 55
  • 이 예제는 최근 1초 동안의 값 중 최대 2개를 저장하도록 설정된 ReplaySubject를 보여줍니다.

 

성능 최적화 주의점

  1. 메모리 관리: ReplaySubject는 값을 버퍼에 저장하기 때문에, 불필요하게 큰 버퍼 크기를 설정하거나 제한 없는 버퍼를 사용하면 메모리 누수가 발생할 수 있습니다.
  2. 적절한 구독 해제: 스트림을 계속해서 구독하면 메모리 누수가 발생할 수 있으므로, 구독 해제를 통해 리소스를 관리해야 합니다.

'개발 공부 > Angular' 카테고리의 다른 글

@ViewChild와 @ViewChildren (2) 기본 활용  (0) 2025.02.15
@ViewChild와 @ViewChildren (1)  (0) 2025.02.13
RxJS의 ReplaySubject / Angular  (0) 2024.12.14
Angular Routing Resolver  (1) 2024.12.11
ng-template / ng-container 차이  (1) 2024.12.10