Skip to content

Commit

Permalink
feat: support attaching effect without store param
Browse files Browse the repository at this point in the history
  • Loading branch information
r13v committed Aug 17, 2023
1 parent e653263 commit 667940f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
22 changes: 22 additions & 0 deletions Effector/Attach.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@

public func attach<Params, MappedParams, Done, Fail>(
name: String? = nil,
effect fx: Effect<MappedParams, Done, Fail>,
map: @escaping (Params) -> MappedParams
) -> Effect<Params, Done, Fail> {
let handler = fx.getCurrent()

let attached = Effect<Params, Done, Fail>(name: name ?? "attach", isDerived: true) { params in
try await handler(map(params))
}

return attached
}

public func attach<Params, Done, Fail>(
name: String? = nil,
effect fx: Effect<Params, Done, Fail>
) -> Effect<Params, Done, Fail> {
return attach(effect: fx, map: { $0 })
}

public func attach<State, Params, Done, Fail>(
name: String? = nil,
store: Store<State>,
Expand Down
25 changes: 25 additions & 0 deletions Tests/EffectorTests/AttachTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,31 @@
import XCTest

final class AttachTests: XCTestCase {
func testAttachCreatesEffect() async throws {
let fx = Effect<Void, Int, Error> { 1 }
let attached = attach(effect: fx)

var isOriginalFxCalled = false
fx.watch { _ in isOriginalFxCalled = true }

var isAttachedFxCalled = false
attached.watch { _ in isAttachedFxCalled = true }

await attached()

XCTAssertFalse(isOriginalFxCalled)
XCTAssertTrue(isAttachedFxCalled)
}

func testAttachWithMappedParams() async throws {
let fx = Effect<Int, Int, Error> { $0 }
let attached = attach(effect: fx, map: { $0 + 10 })

let got = try await attached(1).get()

XCTAssertEqual(got, 11)
}

func testAttachEffect() async throws {
let store = Store(10)
let inc = Effect<Int, Int, Error> { $0 + 1 }
Expand Down

0 comments on commit 667940f

Please sign in to comment.