์ด๋ฏธ์ง๋ฅผ ๊ฐ์ ธ์์ ๋ชจ๋ธ ๊ฐ์ฒด์ ๋งคํํ๋ ์ญํ ์ POP๋ก ๊ตฌํ
Q. StyleRepository๊ฐ ClothesRepository์์ ๋ฐ์ดํฐ๋ฅด ๊ฐ์ ธ์ค๋ฉด ๋๋ ๊ฒ ์๋๊ฐ?
- A. ์กฐ๊ธ ๋นํจ์จ์ ์ธ ๋ฉด์ด ์กด์ฌํ ์ ์์ง๋ง, ์ฌ์ฉ๋๋ Scene์ด ์ ํ ๋ค๋ฅด๊ธฐ ๋๋ฌธ์ ๊ฐ๊ฐ์ Repository๊ฐ ๋ณ๊ฐ๋ก ๋์ํ๋ ๊ฒ์ด ๋ ์ ์ ํ๊ฒ ๋ค๊ณ ์๊ฐํ๊ธฐ์ ๋ณ๋๋ก ๊ตฌํํจ. (ex. Clothes์ ํ์ธํ์ง ์๊ณ , Styleํ๋ฉด๋ง ๋ณผ ์๋ ์๊ธฐ์...)
protocol ImageFetchable {
var imageCacheManager: ImageCacheManager { get }
var imageFileStorage: ImageFileStorageProtocol { get }
func addingImages(to clothesModels: [Clothes]) -> AnyPublisher<[Clothes], Never>
}
extension ImageFetchable {
var imageCacheManager: ImageCacheManager { .shared }
var imageFileStorage: ImageFileStorageProtocol { ImageFileStorage.shared }
func addingImages(to clothesModels: [Clothes]) -> AnyPublisher<[Clothes], Never> {
let clothesWithImagePublishers: [AnyPublisher<Clothes, Never>] = clothesModels.map { model in
if let image = imageCacheManager.get(for: model.id) {
var clothes = model
clothes.image = image
return Just(clothes).eraseToAnyPublisher()
}
return imageFileStorage.load(withID: model.id)
.replaceError(with: UIImage())
.map { image in
var clothes = model
clothes.image = image
return clothes
}
.eraseToAnyPublisher()
}
return Publishers.MergeMany(clothesWithImagePublishers)
.collect()
.eraseToAnyPublisher()
}
}
protocol ImagableModel {
var id: UUID { get }
// ์ด๋ฏธ์ง๋ฅผ ๋งคํํ ๋ ์ ์ฅํ ์ ์์ด์ผ ํ๋ฏ๋ก get set ๋ ๋ค ์๊ตฌ์ฌํญ์ ์ค
var image: UIImage? { get set }
}
// ์ด๋ฏธ์ง๋ฅผ ๋งคํํ ๋ชจ๋ธ ๊ฐ์ฒด์ ImagbleModel ์ฑํ
struct Clothes: ImagableModel {
let id: UUID
var image: UIImage?
...
}
addingImages
๋ฉ์๋์ ImagableModel
๋ก ์ ๋ค๋ฆญ์ ์ค์ผ๋ก์, ์ด๋ฏธ์ง๋ฅผ ๊ฐ์ง ์ ์๋ (ImagebleModel์ ์ฑํํ) ์ด๋ค ํ์
์ ๋ชจ๋ธ์ ๋ํด์๋ ๋งคํ์ด ๊ฐ๋ฅํ๊ฒ ๋์์. > ๊ทธ ์ธ ๋ค๋ฅธ ๋ถ๋ถ์ ๊ตฌํ ๋ก์ง์ ๋์ผ
protocol ImageFetchableRepository {
func addingImages<T: ImagableModel>(to imagableModels: [T]) -> AnyPublisher<[T], RepositoryError>
...
addingImages
๋ฅผ ํธ์ถ๋ง ํ๋ฉด ๋๋ ๊ฐ๋จํ ๋ฐฉ์์ด ๋จfinal class ClothesRepository: ClothesRepositoryProtocol, ImageFetchableRepository {
func fetchClothesList() -> AnyPublisher<ClothesList, RepositoryError> {
let clothesEntities = realmStorage.load(entityType: ClothesEntity.self)
let clothesModelsWithoutImage = clothesEntities.map { $0.toModelWithoutImage() }
return addingImages(to: clothesModelsWithoutImage)
.map { $0.toClothesList() }
.eraseToAnyPublisher()
}