Tunko Development Diary

RxSwift) Creating Operators (repeatElement, deferred, create) λ³Έλ¬Έ

Development/RxSwift

RxSwift) Creating Operators (repeatElement, deferred, create)

Tunko 2022. 5. 31. 16:02

repeatElement

let disposeBag = DisposeBag()
let element = "πŸ‘"

Observable.repeatElement(element)
    .take(10)
    .subscribe { print($0) }
    .disposed(by: disposeBag)

좜λ ₯

next(πŸ‘)
next(πŸ‘)
next(πŸ‘)
next(πŸ‘)
next(πŸ‘)
next(πŸ‘)
next(πŸ‘)
next(πŸ‘)
next(πŸ‘)
next(πŸ‘)
completed

λ™μΌν•œ μš”μ†Œλ₯Ό 반볡적으둜 λ°©μΆœν•˜λŠ” μ—°μ‚°μžμž…λ‹ˆλ‹€.

λ¬΄ν•œμ • λ°˜λ³΅ν•©λ‹ˆλ‹€.

λ”°λΌμ„œ λ°©μΆœλ˜λŠ” 횟수λ₯Ό μ •ν•΄μ£ΌλŠ”κ²Œ μ€‘μš”ν•©λ‹ˆλ‹€. take μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•΄μ„œ 10개의 μš”μ†Œλ§Œ λ°©μΆœλ˜λ„λ‘ ν•΄μ£Όμ—ˆμŠ΅λ‹ˆλ‹€.

deferred

let disposeBag = DisposeBag()
var flag = true

let observable : Observable<Int> = Observable.deferred {
    flag.toggle()
    if flag {
        return Observable.just(1)
    } else {
        return Observable.just(2)
    }
}

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

좜λ ₯

next(2)
completed

νŠΉμ •μ‘°κ±΄μ— 따라 μ˜΅μ €λ²„λΈ”μ„ μƒμ„±ν•˜λŠ” μ—°μ‚°μž μž…λ‹ˆλ‹€. flag 쑰건에 따라 2κ°€ λ“€μ–΄κ°„ justμ˜΅μ €λ²„λΈ”μ΄ κ΅¬λ…λœκ²ƒμ„ 확인할 수 μžˆμŠ΅λ‹ˆλ‹€.

create

just, of, from, range, genarate, repeatElement, deferred λ“±μ˜ μ—°μ‚°μžλŠ” μ˜΅μ €λ²„λΈ”μ— 받은 μš”μ†Œλ₯Ό λ°©μΆœν•˜κ³  completedλ₯Ό ν†΅ν•΄μ„œ μ™„λ£Œλ©λ‹ˆλ‹€

이런 λ™μž‘ 방식을 λ°”κΎΈκΈ° μœ„ν•΄μ„  createλ₯Ό ν†΅ν•΄μ„œ μƒˆλ‘œμš΄ μ˜΅μ €λ²„λΈ”μ„ λ§Œλ“€ ν•„μš”κ°€ μžˆμŠ΅λ‹ˆλ‹€.

createλŠ” Observer을 νŒŒλΌλ―Έν„°λ‘œ λ°›μ•„μ„œ Disposable을 λ¦¬ν„΄ν•©λ‹ˆλ‹€.

return에 유의 ν•΄μ•Ό ν•©λ‹ˆλ‹€. Disposable을 λ¦¬ν„΄ν•˜λΌκ³  λ˜μ–΄μžˆλŠ”λ° 컴파일 μ—λŸ¬κ°€ λ°œμƒν•©λ‹ˆλ‹€. κΌ­ Disposables.create() 둜 λ¦¬ν„΄ν•΄μ€λ‹ˆλ‹€.

createμ˜΅μ €λ²„λΈ”μ„ 톡해 μš”μ†Œλ₯Ό λ°©μΆœν• λ•ŒλŠ” onNextλ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•΄μ•Ό ν•©λ‹ˆλ‹€.

createμ˜΅μ €λ²„λΈ”μ„ μ’…λ£Œν•˜κΈ° μœ„ν•΄μ„  onError, onCompleted 쀑 ν•˜λ‚˜λ₯Ό κΌ­ ν˜ΈμΆœν•΄μ•Όν•©λ‹ˆλ‹€.

let disposeBag = DisposeBag()

enum MyError: Error {
   case error
}

Observable<String>.create { (observer) -> Disposable in
    observer.onNext("λ‚΄κ°€ ν•˜κ³ μ‹Άμ€ 처리")
    observer.onCompleted()
    return Disposables.create()
}
.subscribe{ print($0) }
.disposed(by: disposeBag)

좜λ ₯

next(λ‚΄κ°€ ν•˜κ³ μ‹Άμ€ 처리)
completed

μ›Ήμ—μ„œ html λ¬Έμžμ—΄μ„ λ°›λŠ” μ˜΅μ €λ²„λΈ” 생성

Observable.create { (observer) -> Disposable in
    guard let url = URL(string: "<https://huniroom.tistory.com/>") else {
        observer.onError(MyError.error)
        return Disposables.create()
    }
    
    guard let html = try? String(contentsOf: url, encoding: .utf8) else {
        observer.onError(MyError.error)
        return Disposables.create()
    }
    observer.onNext(html)
    observer.onCompleted()
    
    return Disposables.create()
}
.subscribe{ print($0) }
.disposed(by: disposeBag)

 

λ°˜μ‘ν˜•
Comments