RxSwift(2)

EN·2023년 6월 29일
0

iOS_rxswift

목록 보기
2/4

Operators

just, from

    @IBAction func exMap1() {
        Observable.just("Hello")
            .map { str in "\(str) RxSwift" }
            .subscribe(onNext: { str in
                print(str)
            })
            .disposed(by: disposeBag)
    }
  • just는 단순히 어떤 값만을 단순히 받는? 그냥 그 자체로 Observable객체로 만들어주는 함수이다.
    @IBAction func exFrom1() {
        Observable.from(["RxSwift", "In", "4", "Hours"])
            .subscribe(onNext: { str in
                print(str)
            })
            .disposed(by: disposeBag)
    }
  • from은 array를 Observable sequence로 반환해주는 함수이다.

map, flatmap

    @IBAction func exMap3() {
        Observable.just("800x600")//단순 값은 just!
            .map { $0.replacingOccurrences(of: "x", with: "/") }
            .map { "https://picsum.photos/\($0)/?random" }
            .map { URL(string: $0) }
            .filter { $0 != nil }
            .map { $0! }
            .map { try Data(contentsOf: $0) }
            .map { UIImage(data: $0) }
            .subscribe(onNext: { image in
                self.imageView.image = image
            })
            .disposed(by: disposeBag)
    }
  • map은 observable sequence를 새로운 형태로 project(영사)해주는 함수이다.
    @IBAction func exFlatMap() {
        Observable.just("234")
            .flatMap({
                Observable<String>.just(String($0))
            })
            .subscribe({ n in
                print(n)
            })
            .disposed(by: disposeBag)
    }
  • flatmap은 여러 observable sequence를 하나의 observable sequence로 병합해주는 친구이다.

filter

    @IBAction func exFilter() {
        Observable.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])//배열을 쓸 때는 from,
            .filter { $0 % 2 == 0 }
            .subscribe(onNext: { n in
                print(n)
            })
            .disposed(by: disposeBag)
    }
  • filter는 특정 조건에 맞는 요소만 반환해주는 함수이다.

first

    @IBAction func exFirst() {
        Observable.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])//배열을 쓸 때는 from,
            .first()
            .subscribe({ n in
                print(n)
            })
            .disposed(by: disposeBag)
    }
  • first는 첫 요소만 반환해주는 함수이다.

Observable 연산 결정 트리

언제 어떤 operator를 써야할지에 대해 상황별로 나눠준 결정 트리
참고 : https://reactivex.io/documentation/ko/operators.html

profile
iOS/JUJITSU

0개의 댓글