-2

I am trying to understand Record Publisher.

Here is an example to better understand the case:

var subscriptions = [AnyCancellable]() let pub = Record<Int, Never>(output: [1, 101, 102, 1001, 1002], completion: .finished) // I have used here one of 3 possible inits for that Publisher, and I would like to use exactly that specific one. DispatchQueue.main.asyncAfter(deadline: .now() + 2) { pub.sink { print(">>>1 \($0)") } .store(in: &self.subscriptions) } pub.sink { print(">>>2 \($0)") } .store(in: &subscriptions) 

Output:

 >>>2 1 >>>2 101 >>>2 102 >>>2 1001 >>>2 1002 >>>1 1 >>>1 101 >>>1 102 >>>1 1001 >>>1 1002 

But I don't understand this: where is the part when we record stream of inputs and later it is called for a new subscriptions? For me it would be totally the same using [1, 101, 102, 1001, 1002].publisher.

4
  • I have removed the second question. Commented Jul 3 at 10:06
  • Okay. Is “being able to specify an error/failure completion value” not enough of a difference from Sequence.Publisher? Commented Jul 3 at 10:10
  • is it only difference? I thought that there is some mechanism to wait/record stream and somehow later play it on subscribers.. Commented Jul 3 at 10:14
  • Pretty extensive exploration here: apeth.com/UnderstandingCombine/publishers/publishersrecord.html Commented Jul 3 at 13:14

1 Answer 1

1

You are expected to do this "recording" manually. If the recording is synchronous, you can use init(record:). If the recording is asynchronous, you can create a Record.Recording and call init(recording:).

init(output:completion:) is useful if you already have the recording in the form of an array, not as a Record.Recording.

How is this functionally different from using publisher on an Array? Well, not very much. It allows you to specify an error as the completion of the publisher.

Record(output: someArray, completion: .failure(NSError())) 

is basically the same as

someArray.publisher.setFailureType(to: NSError.self).append(Fail(error: NSError())) 

The more important difference is in their semantics. Asking "why use Record when you can just use Publisher.Sequence" is like asking "why use Just(1) if you can just use [1].publisher", or "why use Empty<Int, Never>() when you can use Int?.none.publisher". Record is more readable and indicates the intent more clearly when you are trying to publish a "record" of some kind.

See also the implementation of Record and Publishers.Sequence in OpenCombine. They have basically the same Inner subscription except Record.Inner completes with the specified Subscribers.Completion.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.