Search code examples
swiftreactive-programmingcombine

Is there a reactive function which executes and passes the original value?


I have a flow which transforms data, acts on it, transform it again, and acts on that. For example:

// Current code
Just(0)
    .map({ $0 + 1 })
    .map({ funcX($0); return $0 })
    .map({ $0 + 1 })
    .map({ funcY($0); return $0 })
    ...

I know reactive programming is about streams, but I would like to call funcX without needing to return the value. Is there a function which passes in the value and automatically passes along the value? Something like:

// Hypothetical
Just(0)
    .map({ $0 + 1 })
    .call({ funcX($0) })
    .map({ $0 + 1 })
    .call({ funcY($0) })
    ...

Note: The above swift needs more syntax to actually compile, just is an example.


Solution

  • No need for a custom operator, one already exists: handleEvents

    Just(0)
        .map({ $0 + 1 })
        .handleEvents(receiveOutput: { funcX($0) })
        .map({ $0 + 1 })
        .handleEvents(receiveOutput: { funcY($0) })
        ...
    

    The handleEvents operator can hook into any part of the publisher/subscriber lifecycle with it's optional parameters:

    • receiveSubscription

    • receiveRequest

    • receiveCancel

    • receiveOutput

    • receiveCompletion