From b7ac23cb54a661c95365ba2ffd26b6312f7bd8d6 Mon Sep 17 00:00:00 2001 From: Oliver Foggin Date: Thu, 14 Dec 2023 18:56:45 +0000 Subject: [PATCH] Add transform function --- .../SubscriberReducer.swift | 43 ++++++++++++++----- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/Sources/ComposableSubscriber/SubscriberReducer.swift b/Sources/ComposableSubscriber/SubscriberReducer.swift index e9eda5f..01bc45f 100644 --- a/Sources/ComposableSubscriber/SubscriberReducer.swift +++ b/Sources/ComposableSubscriber/SubscriberReducer.swift @@ -1,21 +1,37 @@ import ComposableArchitecture extension Reducer { - public func subscribe( - to stream: @escaping () async -> AsyncStream, + public func subscribe( + to stream: @escaping () async -> AsyncStream, on triggerAction: CaseKeyPath, - with responseAction: CaseKeyPath - ) -> _SubscribeReducer { + with responseAction: CaseKeyPath + ) -> _SubscribeReducer { .init( parent: self, on: triggerAction, to: stream, - with: responseAction + with: responseAction, + transform: { $0 } + ) + } + + public func subscribe( + to stream: @escaping () async -> AsyncStream, + on triggerAction: CaseKeyPath, + with responseAction: CaseKeyPath, + transform: @escaping (StreamElement) -> Value + ) -> _SubscribeReducer { + .init( + parent: self, + on: triggerAction, + to: stream, + with: responseAction, + transform: transform ) } } -public struct _SubscribeReducer: Reducer { +public struct _SubscribeReducer: Reducer { @usableFromInline let parent: Parent @@ -23,21 +39,26 @@ public struct _SubscribeReducer: Reducer { let triggerAction: AnyCasePath @usableFromInline - let stream: () async -> AsyncStream + let stream: () async -> AsyncStream @usableFromInline - let responseAction: AnyCasePath + let responseAction: AnyCasePath + + @usableFromInline + let transform: (StreamElement) -> Value init( parent: Parent, on triggerAction: CaseKeyPath, - to stream: @escaping () async -> AsyncStream, - with responseAction: CaseKeyPath + to stream: @escaping () async -> AsyncStream, + with responseAction: CaseKeyPath, + transform: @escaping (StreamElement) -> Value ) { self.parent = parent self.triggerAction = AnyCasePath(triggerAction) self.stream = stream self.responseAction = AnyCasePath(responseAction) + self.transform = transform } public func reduce(into state: inout Parent.State, action: Parent.Action) -> Effect { @@ -51,7 +72,7 @@ public struct _SubscribeReducer: Reducer { effects, .run { send in for await value in await stream() { - await send(responseAction.embed(value)) + await send(responseAction.embed(transform(value))) } } )