Implementation of a ring buffer publisher for Apple's Combine framework.
The publisher produces the first output based on a specified strategy (defaults to .always
). See examples below.
import Foundation
import Combine
let pub = (0..<10).publisher
.ringBuffer(size: 3)
.sink { print($0) }
The above snippet produces the following output:
[0]
[0, 1]
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
Alternatively, when strategy is set to .whenFull
:
import Foundation
import Combine
let pub = (0..<10).publisher
.ringBuffer(size: 3, strategy: .whenFull)
.sink { print($0) }
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
The underlying RingBuffer structure used in this implementation is taken from Ray Wenderlich's Swift Algorithm Club and is written by Matthijs Hollemans.
- OpenCombine — Open-source implementation of Apple's Combine framework
- How to create custom Publisher in Combine
- Extending Combine with a custom ShareReplay operator
Hey, I came across this and just wondered if the same could be achieved using just Scan?
Just wondered if there was any downsides to this approach you can see?