반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- SWIFT
- RxCocoa
- nestjs
- graphql
- Bug
- swift6
- Operater
- @State
- RxSwift
- init?
- RFC1738/1808
- URL(string:)
- dismiss
- IOS
- operator
- ios14
- nonisolated
- @EnvironmentObject
- typeorm
- Operators
- Creating Operators
- @Binding
- NavigationLink
- SwiftUI
- NullObject
- init
- Xcode
- @Environment
- subject
- vim
Archives
- Today
- Total
Tunko Development Diary
RxSwift) ReplaySubject 란? 본문
ReplaySubject는 create메서드를 통해 생성합니다. 생성시 이벤트의 버퍼의 크기를 지정합니다.
버퍼는 메모리에 할당하기 때문에 버퍼크기를 잘 고려해야 합니다. 낭비는 없도록 해줍니다.
let disposeBag = DisposeBag()
enum MyError: Error {
case error
}
let replaySubject = ReplaySubject<Int>.create(bufferSize: 5)
(1...10).forEach {
replaySubject.onNext($0)
}
replaySubject.subscribe{ print("next Event : \\($0)")}
.disposed(by: disposeBag)
출력
next Event : next(6)
next Event : next(7)
next Event : next(8)
next Event : next(9)
next Event : next(10)
next이벤트를 통해 1~10까지 이벤트를 전달했지만 6~10까지만 출력되었습니다.
로그를 보면 버퍼의 크기만큼 이벤트가 방출되는것을 확인할 수 있습니다. 버퍼에는 마지막에 전달된 bufferSize만큼 저장됩니다.
다음으로 새로 구독자를 추가해 봅니다.
let replaySubject = ReplaySubject<Int>.create(bufferSize: 5)
(1...10).forEach {
replaySubject.onNext($0)
}
replaySubject.subscribe{ print("next Event : \\($0)")}
.disposed(by: disposeBag)
replaySubject.subscribe{ print("next Event 2 : \\($0)")}
.disposed(by: disposeBag)
replaySubject.onNext(11)
출력
next Event : next(6)
next Event : next(7)
next Event : next(8)
next Event : next(9)
next Event : next(10)
next Event 2 : next(6)
next Event 2 : next(7)
next Event 2 : next(8)
next Event 2 : next(9)
next Event 2 : next(10)
next Event : next(11)
next Event 2 : next(11)
새로운 구독자를 추가하면 동일한 이벤트가 출력됩니다.
마지막에onNext(11)을 통해 전달한 이벤트는 두 구독자에 방출된것을 확인할 수 있습니다.
여기서 새로 또 구독을 추가하게 되면
replaySubject.subscribe{ print("next Event 3 : \\($0)")}
.disposed(by: disposeBag)
출력
...
next Event 3 : next(7)
next Event 3 : next(8)
next Event 3 : next(9)
next Event 3 : next(10)
next Event 3 : next(11)
replaySubject는 지정된 버퍼 크기만큼 최신 이벤트를 저장하고 구독자에게 전달합니다. 따라서 출력결과를 보면
6,7,8,9,10 이 아닌! 7,8,9,10,11 이 전달된것을 확인할 수 있습니다.
반응형
'Development > RxSwift' 카테고리의 다른 글
RxSwift) Relay (RxSwift 6) (0) | 2022.05.30 |
---|---|
RxSwift) AsyncSubject 란? (0) | 2022.05.30 |
RxSwift) BehaviorSubject 란? (0) | 2022.05.30 |
RxSwift) PublishSubject 란? (0) | 2022.05.30 |
Subject 란? (0) | 2022.05.30 |