ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [RxSwift] Operators (just, from, map, filter)
    프로그래밍/Swift 2021. 4. 15. 17:07

    1. just : 넣어주면 그대로 한번에 다음번으로 전달

    생성 연산자.

    빨간색 구슬은 데이터. 

    아래 화살표는 스트림.

    스트림에 세로로 막대기가 있는것은 데이터가 끝남을 의미 (complete) --> disposableBag에서 사라짐.

     

    func just1() {
    Observable.just("Hello")
        .subscribe(onNext: { s in
            print(s) // Hello
            })
        .disposed(by: disposeBag)
    }
    
    func just2() {
    Observable.just([1,2,3])
        .subscribe(onNext: { arr in
            print(arr) // [1,2,3]
            })
        .disposed(by: disposeBag)
    }

     

    func downloadJson1(_ url: String) -> Observable<String?> {
    	return Observable.create { emitter in
        	emitter.onNext("Hello World")
            emiiter.onCompleted()
            return Disposables.create()
        }
    }
    
    func downloadJson2(_ url: String) -> Observable<String?> {
    	return Observable.just("Hello World")
    }
    
    ...
    
    // Observable로 오는 데이터를 받아서 처리함
    func onLoad() {
    	_ = downloadJson2(MEMBER_LIST_URL)
        	.observeOn(MainScheduler.instance)
            // 메인스레드로 전환. 이렇게 데이터를 중간에 바꾸는 sugar = operator. 
            // 이 한줄이 subscribe안에서 dispatchqueue.main을 하는 같은 효과를 하게됨
            .subscribe(onNext: {json in
            	self.editView.text = json
                self.setVisibleWithAnimation(self.activityIndicator, false)...
              	})
    	}
    }

    데이터를 1개를 내려보낼경우인 위 코드의 downloadJson1, downloadJson2는 동일한 기능을 한다.

     

     

    2. from : 넣어주면 '한개씩' 다음번으로 전달

     

    생성 연산자.

    데이터 (array)가 주어짐.

    연산자(여기서는 from)를 사각형로 표현하고 있음.

     

     

    func from() {
    	Observable.from([1,2,"apple",4])
        	.subscribe(onNext: { element in
            	print(element)
            })
            .disposed(by: disposeBag)
    }
    
    // 1
    // 2
    // apple
    // 4

     

     

    3. map :  Observable이 배출한 항목에 함수를 적용

    Transforming.

    Observable(stream)에서 데이터들이 시간 순으로 나열되어있고

    그것이 어떤 처리 후에 아래로 내려온다는 것을 의미함.

    1이 10이 되고, 2가 20, 3이 30 ... 

     

    처음부터 map을 사용할 수는 없음(기존의 stream을 받아야함)

    --> Observable.map ... 이런식으로 시작하면 안된다는 것을 의미함

    func exMap1() {
    	Observable.just("Hello") // Hello가 내려가고
        	.map { str in "\(str) RxSwift" } // Hello와 RxSwift 붙은게 내려가고
            .subscribe(onNext: { str in 
            	print(str)	// Hello RxSwift
            })
            .disposed(by: disposeBag)
    }

     

    func exMap2() {
    	Observable.from(["apple", "bear"])
        	.map { $0.count }
            .subscribe(onNext: { str in 
            	print(str)
            })
            .disposed(by: disposeBag)
    }
    
    // 5
    // 4 --> 이렇게 하나씩 내려보내는걸 stream이라고 함

     

    4. filter : 조건을 만족하는 항목들만 배출

    filtering.

     

    func exFilter() {
    	Observable.from([1,2,3,4,5])
        	.filter { $0 % 2 == 0 } // true일때만 아래로 내려감.
            .subscribe(onNext: { n in
            	print(n)
            })
            .disposed(by: disposeBag)
    }
    
    // 2
    // 4

     

    사용예시

    func example() {
    	Observable.just("800x600")
        	.map { $0.replacingOccurrences(of: "x", with: "/") } // "800/600"
            .map { "https://picsum.photos/\($0)/?random" }	// "https://picsum.photos/800/600/?random"
            .map { URL(string: $0) }	// URL?
            .filter { $0 != nil }	// URL객체가 nil이면 안내려감
            .map { $0! }	// URL! (강제 언래핑)
            .map { try Data(contentsOf: $0) } // Data
            .map { UIImage(data: $0) }	// UIImage?
            .subscribe(onNext: { image in
            	self.imageView.image = image
            })
            .disposed(by: disposeBag)
    }
    반응형

    '프로그래밍 > Swift' 카테고리의 다른 글

    [RxSwift] Operators (scan, window)  (0) 2021.04.16
    [RxSwift] subject  (0) 2021.04.16
    [RxSwift] subscribe, next, error, completed  (0) 2021.04.15

    댓글

Designed by Tistory.