Skip to content

Latest commit

 

History

History
40 lines (28 loc) · 1.89 KB

pattern-assign.adoc

File metadata and controls

40 lines (28 loc) · 1.89 KB

Creating a subscriber with assign

Goal
  • To use the results of a pipeline to set a value, often a property on a user interface view or control, but any KVO compliant object can be the provider.

References
See also
Code and explanation

Assign is a subscriber that’s specifically designed to apply data from a publisher or pipeline into a property, updating that property whenever it receives data. Like sink, it activates when created and requests an unlimited data. Assign requires the failure type to be specified as <Never>, so if your pipeline could fail (such as using an operator like tryMap) you will need to convert or handle the failure cases before using .assign.

simple assign
let cancellablePipeline = publishingSource (1)
    .receive(on: RunLoop.main) (2)
    .assign(to: \.isEnabled, on: yourButton) (3)

cancellablePipeline.cancel() (4)
  1. .assign is typically chained onto a publisher when you create it, and the return value is cancellable.

  2. If .assign is being used to update a user interface element, you need to make sure that it is being updated on the main thread. This call makes sure the subscriber is received on the main thread.

  3. Assign references the property being updated using a key path, and a reference to the object being updated.

  4. At any time you can cancel to terminate and invalidate pipelines with cancel(). Frequently, you cancel the pipelines when you deactivate the objects (such as a viewController) that are getting updated from the pipeline.