Recursive function inside Effect.run(_:) #837
Unanswered
nikitamounier
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello there!
I have a question on the behaviour of the
Effect.run(_:)
function. Basically, I'm using the Network framework in my app for some peer-to-peer functionality. Therefore, I've modelled all my dependencies in the TCA way, including aConnectionClient
, which represents the bi-directional connections the devices will have. It looks like this:Then, with my
.live
implementation, I have a dictionary which holds all my connections:The
create(_:_:)
endpoint on theConnectionClient
is what initializes a connection and then sends back any state updates, while thestartConnection(_:)
endpoint is what starts the connection on a queue, and sends back any messages it receives.Unfortunately, the API for receiving messages in the Network framework is quite weird. It looks like a pretty normal method on the surface, with a single callback closure parameter:
However, this function registers a handler for a single message, and then the handler will be discarded and therefore not used for any messages afterwards. So if we want to receive messages indefinitely, it's customary to use a recursive function to register an unlimited amount of handlers for an unlimited amount of messages.
So, I'm using a recursive function inside of my
startConnection(_:)
endpoint. The endpoint usesEffect.run
since I want to send back an event whenever it receives a message. It looks like this:Thing is, I'm not sure if this is allowed. I'm supposed to return an
AnyCancellable
in theEffect.run
, but since I'm using a recursive function, won't it just never return until there is an error? Would there be another way of calling.receiveMessage(_:)
indefinitely while still using theEffect.run
function?The full source code for the file can be found here.
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions