From 09ffeb3693fda357d8e1de3fc4fc39210445e6fb Mon Sep 17 00:00:00 2001 From: Mohammad Bashtnai Date: Sun, 10 Dec 2023 14:14:28 +0330 Subject: [PATCH] Integrition with modern concurrency --- Sources/Loadable/Publisher+Extensions.swift | 8 ++---- Sources/Loadable/Task+Extensions.swift | 21 ++++++++++++++ Tests/LoadableTests/TaskExtensionsTest.swift | 30 ++++++++++++++++++++ 3 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 Sources/Loadable/Task+Extensions.swift create mode 100644 Tests/LoadableTests/TaskExtensionsTest.swift diff --git a/Sources/Loadable/Publisher+Extensions.swift b/Sources/Loadable/Publisher+Extensions.swift index b2ae294..b7e0ba4 100644 --- a/Sources/Loadable/Publisher+Extensions.swift +++ b/Sources/Loadable/Publisher+Extensions.swift @@ -13,9 +13,8 @@ public extension Publisher { /// convert a publisher data to states of a label /// - returns: A publisher with ``Loadable`` output type func mapToLoadable() -> AnyPublisher, Never> { - self - .map { - Loadable.loaded($0) + self.map { + Loadable.loaded($0) }.catch { Just(Loadable.failed($0)) @@ -25,8 +24,7 @@ public extension Publisher { // when subscripton happend set state of loadable to loading .merge(with: Just(Loadable.isLoading)) .eraseToAnyPublisher() - -} + } } /// used type erasure technique to extend publisher where output type is ``Loadable`` diff --git a/Sources/Loadable/Task+Extensions.swift b/Sources/Loadable/Task+Extensions.swift new file mode 100644 index 0000000..0dd059b --- /dev/null +++ b/Sources/Loadable/Task+Extensions.swift @@ -0,0 +1,21 @@ +// +// File.swift +// +// +// Created by Mohammad Bashtani on 12/10/23. +// + +import Foundation + +@available(macOS 10.15, *) +extension Task { + func mapToLoadable() async -> Loadable { + do { + let data = try await self.value + return .loaded(data) + } + catch { + return .failed(error) + } + } +} diff --git a/Tests/LoadableTests/TaskExtensionsTest.swift b/Tests/LoadableTests/TaskExtensionsTest.swift new file mode 100644 index 0000000..8d4f5cf --- /dev/null +++ b/Tests/LoadableTests/TaskExtensionsTest.swift @@ -0,0 +1,30 @@ +// +// File.swift +// +// +// Created by Mohammad Bashtani on 12/10/23. +// + +import Foundation +@testable import Loadable +import XCTest + +final class TaskExtensionsTest: XCTestCase { + func test_MapToLoadable_returning_value() async throws { + let valueToBeReturn = "value" + var loadable: Loadable = .idle + loadable = await Task.init { + return valueToBeReturn + }.mapToLoadable() + XCTAssertEqual(loadable.value, valueToBeReturn) + } + + func test_MapToLoadable_throwing_error() async throws { + let errorToBeThrown = LoadableError() + var loadable: Loadable = .idle + loadable = await Task.init { + throw errorToBeThrown + }.mapToLoadable() + XCTAssertEqual(loadable.error?.localizedDescription, errorToBeThrown.localizedDescription) + } +}