在合并中,我如何依次运行一系列期货?

问题描述 投票:1回答:1

是否有一个Combine操作符将按顺序运行一系列期货,在开始下一个期货之前将其运行到完成?

我可以用非常凌乱的方式做到这一点:

f1
.flatMap { _ in 
  f2
}.flatMap { _ in 
  f3
}.flatMap { _ in 
  // ... 
}

但是我更喜欢这样的东西:

sequence(f1, f2, f3, ...)

在某些框架中,这看起来像:

f1.then { f2 }.then { f3 }
ios macos foundation combine
1个回答
0
投票

关键是将Future封装在Deferred中,这样直到时间到时才执行:

let f1 = Deferred { Future<Int, Error> { result in

    }
}
let f2 = Deferred { Future<Int, Error> { result in

    }
}
let f3 = Deferred { Future<Int, Error> { result in

    }
}
let jobs = f1
    .append(f2)
    .append(f3)

cancellable = jobs.sink(receiveCompletion: { (completion) in
    print("all three jobs done or one errored.")
}, receiveValue: { value in
    print("value of job:", value)
})
© www.soinside.com 2019 - 2024. All rights reserved.