Created
February 20, 2019 17:07
-
-
Save ksoftllc/51c426d3cd739a5c309486a25e22ae14 to your computer and use it in GitHub Desktop.
This file contains 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
// SearchResultViewModel.swift | |
// RxExample | |
// | |
// Created by Krunoslav Zaher on 4/3/15. | |
// Modified by Chuck Krutsinger on 2/20/19. | |
// | |
// Copyright © 2015 Krunoslav Zaher. All rights reserved. | |
// | |
import RxSwift | |
import RxCocoa | |
class SearchResultViewModel { | |
var title: Driver<String> | |
var imageURLs: Driver<[URL]> | |
init(searchResult: WikipediaSearchResult) { | |
let URLs = configureImageURLs(searchResult) | |
self.imageURLs = URLs.asDriver(onErrorJustReturn: []) | |
self.title = configureTitle(URLs, searchResult).asDriver(onErrorJustReturn: "Error during fetching") | |
} | |
} | |
fileprivate func configureTitle(_ imageURLs: Observable<[URL]>, | |
_ searchResult: WikipediaSearchResult) -> Observable<String> | |
{ | |
let loadingValue: [URL]? = nil | |
return imageURLs | |
.map(Optional.init) | |
.startWith(loadingValue) | |
.map { URLs in | |
if let URLs = URLs { | |
return "\(searchResult.title) (\(URLs.count) pictures)" | |
} | |
else { | |
return "\(searchResult.title) (loading…)" | |
} | |
} | |
.retryOnBecomesReachable("⚠️ Service offline ⚠️", reachabilityService: Dependencies.sharedDependencies.reachabilityService) | |
} | |
fileprivate func configureImageURLs(_ searchResult: WikipediaSearchResult) -> Observable<[URL]> | |
{ | |
return DefaultWikipediaAPI.sharedAPI.articleContent(searchResult) | |
.observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler) | |
.map { page in | |
do { | |
return try parseImageURLsfromHTMLSuitableForDisplay(page.text as NSString) | |
} catch { | |
return [] | |
} | |
} | |
.share(replay: 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment