Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions Sources/Loadable/Publisher+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Loadable<Output>, Never> {
self
.map {
Loadable<Output>.loaded($0)
self.map {
Loadable<Output>.loaded($0)

}.catch {
Just(Loadable.failed($0))
Expand All @@ -25,8 +24,7 @@ public extension Publisher {
// when subscripton happend set state of loadable to loading
.merge(with: Just(Loadable<Output>.isLoading))
.eraseToAnyPublisher()

}
}
}

/// used type erasure technique to extend publisher where output type is ``Loadable``
Expand Down
21 changes: 21 additions & 0 deletions Sources/Loadable/Task+Extensions.swift
Original file line number Diff line number Diff line change
@@ -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<Success> {
do {
let data = try await self.value
return .loaded(data)
}
catch {
return .failed(error)
}
}
}
30 changes: 30 additions & 0 deletions Tests/LoadableTests/TaskExtensionsTest.swift
Original file line number Diff line number Diff line change
@@ -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<String> = .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<String> = .idle
loadable = await Task.init {
throw errorToBeThrown
}.mapToLoadable()
XCTAssertEqual(loadable.error?.localizedDescription, errorToBeThrown.localizedDescription)
}
}