0

I want a Publisher similar to Just except it should emit multiple values, and then complete the stream.

Let's call it JustSeveral:

func fibonacci(_ number: Int) -> AnyPublisher<Int, Never> {
  Future { ... }.eraseToAnyPublisher()
}

JustSeveral([293, 18, 104])
  .flatMap { fibonacci($0) }
  .sink { print($0) }

Is there a way to combine operators with Just to get the same thing, or do I need to build this Publisher myself?

Note: Any solution should be able to handle an arbitrary number of elements in the array, not just 3.


For example, if we had an uncollect operator, this would be trivial:

Just([293, 18, 104])
  .uncollect { $0 }
  .flatMap { fibonacci($0) }
  .sink { print($0) }
Senseful
  • 86,719
  • 67
  • 308
  • 465

2 Answers2

3

Importing Combine extends Array with a computed property called publisher, which returns a Sequence<Array<Int>, Never>, which is a Publisher. So you can just do:

[293, 18, 104]
    .publisher
    .flatMap { fibonacci($0) }
    .sink { print($0) }

However, Apple's API documentation blows chunks, and I don't think there's a page that documents Array.publisher.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • This is exactly what I was missing. I found some documentation here: https://heckj.github.io/swiftui-notes/#reference-sequence – Senseful May 13 '21 at 17:35
0

Update: You should use the built-in .publisher method.


Original answer:

One solution is to make the publisher wait until there is a subscription and then emit values:

public struct JustSeveral<Value>: Publisher {
  public init(_ outputs: [Value]) {
    self.outputs = outputs
  }

  public var outputs: [Value]

  public typealias Output = Value
  public typealias Failure = Never

  public func receive<Downstream: Subscriber>(subscriber: Downstream) where Downstream.Input == Output, Downstream.Failure == Failure {
    let subject = PassthroughSubject<Value, Never>()
    subject
      .subscribe(subscriber)

    outputs.forEach { subject.send($0) }
    subject.send(completion: .finished)
  }
}

Although this works, I don't know if it's the best solution since it only emits values upon a subscription. I'm not certain that that is how Just works.

Senseful
  • 86,719
  • 67
  • 308
  • 465