Skip to content

Commit

Permalink
Improvement
Browse files Browse the repository at this point in the history
  • Loading branch information
Mehran Kamalifard authored and Mehran Kamalifard committed Aug 8, 2024
1 parent ea63aa6 commit cd15758
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 23 deletions.
39 changes: 19 additions & 20 deletions EasyCrypto/Base/BaseViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,33 +33,32 @@ open class DefaultViewModel: BaseViewModel, ObservableObject {
var loadingState = CurrentValueSubject<ViewModelStatus, Never>(.dismissAlert)
let subscriber = Cancelable()

func call<ReturnType>(callWithIndicator: Bool = true,
argument: AnyPublisher<ReturnType?,
APIError>,
callback: @escaping (_ data: ReturnType?) -> Void) {

func call<ReturnType>(
callWithIndicator: Bool = true,
argument: AnyPublisher<ReturnType, APIError>,
callback: @escaping (_ data: ReturnType) -> Void
) {
if callWithIndicator {
self.loadingState.send(.loadStart)
}

let completionHandler: (Subscribers.Completion<APIError>) -> Void = { [weak self] completion in
switch completion {
case .failure(let error):
self?.loadingState.send(.dismissAlert)
self?.loadingState.send(.emptyStateHandler(title: error.desc))
case .finished:
self?.loadingState.send(.dismissAlert)
}
}

let resultValueHandler: (ReturnType?) -> Void = { data in
callback(data)
}

argument
.subscribe(on: WorkScheduler.backgroundWorkScheduler)
.receive(on: WorkScheduler.mainScheduler)
.sink(receiveCompletion: completionHandler, receiveValue: resultValueHandler)
.sink(
receiveCompletion: { [weak self] completion in
switch completion {
case .failure(let error):
self?.loadingState.send(.dismissAlert)
self?.loadingState.send(.emptyStateHandler(title: error.desc))
case .finished:
self?.loadingState.send(.dismissAlert)
}
},
receiveValue: { data in
callback(data)
}
)
.store(in: subscriber)
}
}
16 changes: 13 additions & 3 deletions EasyCrypto/Presentation/Detail/ViewModel/DetailViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,22 @@ final class DetailViewModel: ObservableObject {
}

func addToWishlist(_ data: MarketsPrice) {
_ = try? self.repository.save(data)
do {
try repository.save(data)
} catch {
// Handle error, e.g., log it or show an alert
print("Error saving to wishlist: \(error.localizedDescription)")
}
}

func deleteFromWishlist(_ data: MarketsPrice) {
guard let name = data.name else {return}
_ = try? self.repository.deleteByID(name)
guard let name = data.name else { return }
do {
try repository.deleteByID(name)
} catch {
// Handle error, e.g., log it or show an alert
print("Error deleting from wishlist: \(error.localizedDescription)")
}
}

func checkIfItemExist(_ data: MarketsPrice) -> Bool {
Expand Down

0 comments on commit cd15758

Please sign in to comment.