그렇다면 이거 없이도 우리는 비동기처리를 하는 방법을 안다. 바로
1. Notification Center : 사용자의 이벤트처리를 비동기적으로 기다리다가 받으면 이벤트 실행
2. Delegate Pattern : 정의만 해놓고 나중에 실행되도록
3. GCD!! : 비동기들은 global queue로 넘기고 ui관련된것들만 main queue에서 처리하도록 해주었다.
4. 클로져 : 클래스가 실행여부를 결정할 수 있다
하지만 위 4가지 단점은 콜백지옥에 빠질 위험이 크고 가독성이 떨어지게 된다.
그래서 나온것이 ReactiveX swift!!
Observable<Int>.just(1)
Observable<Int>.of(1,2,3,4,5)
Observable<Int>.of([1,2,3,4,5])
하나의 시퀀스를 만드는 방식이다. 하지만 생성만한다고 아무것도 이루어지지 않는다. 여기서 필요한 것이 subscribe
Observable<Int>.of(1,2,3,4).subscribe(onNext: {
print($0)})
이러면 1 2 3 4가 출력이 된다.만약 onNext:없이 그냥 했다면 Next(1)..Next(4)후 complete까지 출력
Observable<Void>.empty().subscribe{print($0)}
Observable.never().subscribe(onNext:{print($0)},onCompleted:{print("completed")})
이건 아무것도 출력이 되지 않는다. 작동은 하지만 아무런 것도 리턴값으로 내보내주지 않는다.
Observable.range(start:1, count: 9).subscribe(onNext : {
print("2*/($0) = ")})
start값부터 카운트까지 하나씩늘리면서 range를 만드는 operator
Observable<Int>.of(1,2,3,4).subscribe(onNext: {
print($0)}).dispose()
구독을 취소한후에는 이벤트방출이 더이상이루어지지 않는다.비슷한 방법으로 disposeBag방식도 있다. disposeBag이 구독을 할때마다 가지고 있다가 할당해제할때 모든 저장한값에 대해 해지를 한다. 그러면 왜? 메모리누수!!
Observable.create{observer -> Disposable in
observer.onNext(1) //observer.on(.next(1))
observer.onCompleted()
observer.onNext(2)
return Disposable.create()}.subscribe{print($0)}.dispose(by:disposeBag)
결과값은 1만 출력된다. 왜? oncomplete를 통해 observable이 종료되었기에!! 2가 출력이 안된다.
옵저블을 생성하는 방식중 하나. Disposable형태로 리턴하는 클로저이다
Observable.deferred{
Observable.of(1,2)}.subscribe{print($0)}
! 12
4또다른 observable생성방식이다. 이건 감싸기에 내부에는 또다른 observable를 선언해서 만들수 있다.
Single<String>.just("V").subscribe(onSuccess :{}, onFailure:{}, onDisposed:{})
single의 onsuccess는 observable의 onNext+onCompleted 즉 하나의 이벤트를 발생시킨후 바로종료
싱글은 하나의 이벤트만 받을 수있다.
observable.asSingle()도 위와 같은거!
Completable.create{observer -> Disposable in observer(.error(TraitsError.completable))
return DisPosable.create()}
.subscribe(onCompleted:{}, onError:{print("error")},onDisposed:{print("dispose")}).disposed(by: disposeBag)
completable은 반환값이 없다. 즉 next값이 없다. 결국 출력은 error
With a combination of Crossword planet fitness normal prices
and tests your vocabulary skills by challenging you to find the hidden You can choose words with three vowels and all five different letters to expand the range.