-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathFavoriteViewModel.swift
77 lines (65 loc) · 2.15 KB
/
FavoriteViewModel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
// FavoriteViewModel.swift
// iOSDesignPatternSamples
//
// Created by marty-suzuki on 2017/09/10.
// Copyright © 2017年 marty-suzuki. All rights reserved.
//
import Combine
import Foundation
import GithubKit
protocol FavoriteViewModelType: AnyObject {
var output: FavoriteViewModel.Output { get }
var input: FavoriteViewModel.Input { get }
}
final class FavoriteViewModel: FavoriteViewModelType {
let output: Output
let input: Input
var favorites: [Repository] {
favoriteModel.favorites
}
private let favoriteModel: FavoriteModelType
private var cancellable = Set<AnyCancellable>()
init(
favoriteModel: FavoriteModelType
) {
self.favoriteModel = favoriteModel
let _selectedIndexPath = PassthroughSubject<IndexPath, Never>()
let _selectedRepository = PassthroughSubject<Repository, Never>()
self.output = Output(
favorites: favoriteModel.favorites,
relaodData: favoriteModel.favoritePublisher.map { _ in }.eraseToAnyPublisher(),
selectedRepository: _selectedRepository.eraseToAnyPublisher()
)
self.input = Input(selectedIndexPath: _selectedIndexPath.send)
_selectedIndexPath
.map { favoriteModel.favorites[$0.row] }
.sink {
_selectedRepository.send($0)
}
.store(in: &cancellable)
favoriteModel.favoritePublisher
.assign(to: \.favorites, on: output)
.store(in: &cancellable)
}
}
extension FavoriteViewModel {
struct Input {
let selectedIndexPath: (IndexPath) -> Void
}
final class Output {
@Published
fileprivate(set) var favorites: [Repository]
let relaodData: AnyPublisher<Void, Never>
let selectedRepository: AnyPublisher<Repository, Never>
init(
favorites: [Repository],
relaodData: AnyPublisher<Void, Never>,
selectedRepository: AnyPublisher<Repository, Never>
) {
self.favorites = favorites
self.relaodData = relaodData
self.selectedRepository = selectedRepository
}
}
}