[Swift] Observable 기본 문법 정리 7

준수·2022년 10월 30일
0
post-thumbnail

공통 : RxSwift import, DisposeBag 인스턴스 생성

import RxSwift

let disposeBag = DisposeBag()

입력

print("-------replay-------")
let greeting = PublishSubject<String>()
let parrot = greeting.replay(1)
parrot.connect() // replay는 connect를 필수로 사용해야 함

greeting.onNext("1. Hello~")
greeting.onNext("2. Hi~")

parrot
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

greeting.onNext("3. Bye~")

출력

-------replay-------
2. Hi~
3. Bye~

입력

print("-------replayAll-------")
let drStrange = PublishSubject<String>()
let timeStone = drStrange.replayAll()
timeStone.connect()

drStrange.onNext("도르마무")
drStrange.onNext("거래를 하러 왔다.")

timeStone
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

출력

-------replayAll-------
도르마무
거래를 하러 왔다.

입력

print("-------buffer-------")
let source = PublishSubject<String>()

var count = 0
let timer = DispatchSource.makeTimerSource()

timer.schedule(deadline: .now() + 2, repeating: .seconds(1))
timer.setEventHandler {
    count += 1
    source.onNext("\(count)")
}
timer.resume()

source
    .buffer(
        timeSpan: .seconds(2),
        count: 2, // 최대 2개의 요소를 갖는 array를 방출
        scheduler: MainScheduler.instance
    )
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

출력

-------buffer-------
[]
["1", "2"]
["3", "4"]
["5"]
["6", "7"]
["8", "9"]
["10"]
...

입력

print("-------window-------")
let willMakeObservableCount = 5
let willMakeObservableTime = RxTimeInterval.seconds(2)

let window = PublishSubject<String>()

var windowCount = 0
let windowTimerSource = DispatchSource.makeTimerSource()
windowTimerSource.schedule(deadline: .now() + 2, repeating: .seconds(1))
windowTimerSource.setEventHandler {
    windowCount += 1
    window.onNext("\(windowCount)")
}
windowTimerSource.resume()

window
    .window(
        timeSpan: willMakeObservableTime,
        count: willMakeObservableCount,
        scheduler: MainScheduler.instance
    )
    .flatMap { windowObservable -> Observable<(index: Int, element: String)> in
        return windowObservable.enumerated()
    }
    .subscribe(onNext: {
        print("\($0.index)번째 Observable의 요소 \($0.element)")
    })
    .disposed(by: disposeBag)

출력

-------window-------
0번째 Observable의 요소 1
0번째 Observable의 요소 2
1번째 Observable의 요소 3
0번째 Observable의 요소 4
1번째 Observable의 요소 5
0번째 Observable의 요소 6
1번째 Observable의 요소 7
0번째 Observable의 요소 8
1번째 Observable의 요소 9
...

입력

print("-------delaySubscription-------")
let delaySource = PublishSubject<String>()

var delayCount = 0
let delayTimeSource = DispatchSource.makeTimerSource()
delayTimeSource.schedule(deadline: .now() + 2, repeating: .seconds(1))
delayTimeSource.setEventHandler {
    delayCount += 1
    delaySource.onNext("\(delayCount)")
}
delayTimeSource.resume()

delaySource
    .delaySubscription(.seconds(5), scheduler: MainScheduler.instance) // 지정 시간 이후로 구독 시작
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

출력

-------delaySubscription-------
4
5
6
7
8
9
10
...

입력

print("-------delay-------")
let delaySubject = PublishSubject<Int>()

var delayCount = 0
let delayTimerSource = DispatchSource.makeTimerSource()
delayTimerSource.schedule(deadline: .now(), repeating: .seconds(1))
delayTimerSource.setEventHandler {
    delayCount += 1
    delaySubject.onNext(delayCount)
}
delayTimerSource.resume()

delaySubject
    .delay(.seconds(3), scheduler: MainScheduler.instance)
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

출력

-------delay-------
2
3
4
5
6
7
...

입력

print("-------interval-------")
Observable<Int>
    .interval(.seconds(3), scheduler: MainScheduler.instance)
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

출력 (3초 간격으로 출력됨)

-------interval-------
0
1
2
3
4
5
...

입력

print("-------timer-------")
Observable<Int>
    .timer(
        .seconds(1),
        period: .seconds(2),
        scheduler: MainScheduler.instance
    )
    .subscribe(onNext: {
        print($0)
    })
    .disposed(by: disposeBag)

출력

-------timer-------
0
1
2
3
4
5
6
7
...

입력

// 추가로 아래 3개 import 필요! (Playground 내 UI 미리보기를 위함)
import RxCocoa
import UIKit
import PlaygroundSupport

print("-------timeout-------")
let errorIfNotClick = UIButton(type: .system)
errorIfNotClick.setTitle("눌러주세요!", for: .normal)
errorIfNotClick.sizeToFit()

PlaygroundPage.current.liveView = errorIfNotClick

errorIfNotClick.rx.tap
    .do(onNext: {
        print("tap")
    })
    .timeout(.seconds(5), scheduler: MainScheduler.instance)
    .subscribe {
        print($0)
    }
    .disposed(by: disposeBag)

출력

profile
🤭Swift My Velog🤭

0개의 댓글