Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. // SearchResultViewModel.swift
  2. // RxExample
  3. //
  4. // Created by Krunoslav Zaher on 4/3/15.
  5. // Modified by Chuck Krutsinger on 2/20/19.
  6. //
  7. // Copyright © 2015 Krunoslav Zaher. All rights reserved.
  8. //
  9.  
  10. import RxSwift
  11. import RxCocoa
  12.  
  13. class SearchResultViewModel {
  14.  
  15. var title: Driver<String>
  16. var imageURLs: Driver<[URL]>
  17.  
  18. init(searchResult: WikipediaSearchResult) {
  19. let URLs = configureImageURLs(searchResult)
  20.  
  21. self.imageURLs = URLs.asDriver(onErrorJustReturn: [])
  22. self.title = configureTitle(URLs, searchResult).asDriver(onErrorJustReturn: "Error during fetching")
  23. }
  24. }
  25.  
  26. fileprivate func configureTitle(_ imageURLs: Observable<[URL]>,
  27. _ searchResult: WikipediaSearchResult) -> Observable<String>
  28. {
  29. let loadingValue: [URL]? = nil
  30.  
  31. return imageURLs
  32. .map(Optional.init)
  33. .startWith(loadingValue)
  34. .map { URLs in
  35. if let URLs = URLs {
  36. return "\(searchResult.title) (\(URLs.count) pictures)"
  37. }
  38. else {
  39. return "\(searchResult.title) (loading…)"
  40. }
  41. }
  42. .retryOnBecomesReachable("⚠️ Service offline ⚠️", reachabilityService: Dependencies.sharedDependencies.reachabilityService)
  43. }
  44.  
  45. fileprivate func configureImageURLs(_ searchResult: WikipediaSearchResult) -> Observable<[URL]>
  46. {
  47. return DefaultWikipediaAPI.sharedAPI.articleContent(searchResult)
  48. .observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler)
  49. .map { page in
  50. do {
  51. return try parseImageURLsfromHTMLSuitableForDisplay(page.text as NSString)
  52. } catch {
  53. return []
  54. }
  55. }
  56. .share(replay: 1)
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement