是否有执行并传递原始值的反应函数?

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

我有一个流程,可以转换数据、对其进行操作、再次对其进行转换,然后对其进行操作。例如:

// Current code
Just(0)
    .map({ [=10=] + 1 })
    .map({ funcX([=10=]); return [=10=] })
    .map({ [=10=] + 1 })
    .map({ funcY([=10=]); return [=10=] })
    ...

我知道反应式编程是关于流的,但我想调用 funcX 而不需要 return 值。有没有传入值并自动传递值的函数?类似于:

// Hypothetical
Just(0)
    .map({ [=11=] + 1 })
    .call({ funcX([=11=]) })
    .map({ [=11=] + 1 })
    .call({ funcY([=11=]) })
    ...

注意:以上swift实际编译需要更多的语法,只是一个例子。

当然你可以写你自己的运算符,但对我来说有更简单的方法,基于默认运算符,有处理程序,例如:

extension Publisher {

/// Republishes all elements that match a provided closure.
///
/// - Parameter isIncluded: A closure that takes one element and returns a Boolean value indicating whether to republish the element.
/// - Returns: A publisher that republishes all elements that satisfy the closure.
public func filter(_ isIncluded: @escaping (Self.Output) -> Bool) -> Publishers.Filter<Self>

所以你的案例看起来像

.filter({ funcX([=11=]); return true })

因此,您拥有透明的流,并且可以对下游值执行任何回调。

你甚至可以把它包起来,比如

extension Publisher {
    public func call(_ closure: @escaping (Self.Output) -> Void) -> Publishers.Filter<Self> {
        return self.filter({ closure([=12=]); return true })
    }
}

不需要自定义运算符,一个已经存在:handleEvents

Just(0)
    .map({ [=10=] + 1 })
    .handleEvents(receiveOutput: { funcX([=10=]) })
    .map({ [=10=] + 1 })
    .handleEvents(receiveOutput: { funcY([=10=]) })
    ...

handleEvents 运算符可以使用其可选参数挂接到 publisher/subscriber 生命周期的任何部分:

  • 接收订阅

  • 接收请求

  • 接收取消

  • 接收输出

  • 接收完成