Last active
April 8, 2017 02:29
-
-
Save devxoul/f26ff3c693cea5b600e205d42b6f2fea to your computer and use it in GitHub Desktop.
Swift Korea 질문에 대한 답변
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
뭔가 퍼즐같은 RxSwift 질문입니다. | |
서버에 3 페이지의 분량을 한꺼번에 요청하려는데, | |
요청은 동시에 보내고 응답은 순서대로 처리하고 싶습니다. | |
테스트 시나리오: | |
각 요청(Observable)들은 subscribe 될 때 request가 시작 | |
각 요청의 request에는 2, 4, 2초씩 걸린다고 가정 | |
-> 2초 후 첫 페이지가 뜨고 | |
-> 추가로 2초 후 나머지가 전부 뜨는 | |
상황을 원하고 있습니다. | |
====================== | |
1) concat으로 묶으면 | |
- request가 동시에 들어가지 않아서, | |
- 6초째에 두번째 페이지, 8초째에 마지막 페이지가 추가 | |
2) merge로 묶으면 | |
- request는 동시에 들어가지만, | |
- 4초만에 모든 작업이 끝나지만 순서가 보장이 안 되는 상황 | |
3) zip으로 묶어서 flatMap으로 처리 | |
- request는 동시에 들어가지만, 다 끝날때까지 기다리므로, | |
- 첫 페이지가 뜨는데 4초가 걸립니다. | |
====================== | |
어떻게 해야 원하는대로 처리를 할 수 있을까요? | |
*/ | |
func requestPage1() -> Observable<[String]> { | |
return Observable.just(["A", "B"]).delay(2, scheduler: MainScheduler.instance) | |
} | |
func requestPage2() -> Observable<[String]> { | |
return Observable.just(["C", "D"]).delay(4, scheduler: MainScheduler.instance) | |
} | |
func requestPage3() -> Observable<[String]> { | |
return Observable.just(["E", "F"]).delay(2, scheduler: MainScheduler.instance) | |
} | |
example("My example") { | |
let requestFirstPage = requestPage1() // [A, B] | |
let requestNextPages = Observable.combineLatest(requestPage2(), requestPage3()) { $0 + $1 } // [C, D] + [E, F] | |
.startWith([]) // 아래 combineLatest애서 최초 1회 실행되기 위해 초기값을 빈 값으로 지정 | |
let items = Observable.combineLatest(requestFirstPage, requestNextPages) { $0 + $1 } | |
items.subscribe(onNext: { value in | |
print(value) | |
// 2s: [A, B] | |
// 4s: [A, B, C, D, E, F] | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment