跳转至
Structure

SubscriptionView

A view that subscribes to a publisher with an action.

Declaration

@frozen struct SubscriptionView<PublisherType, Content> : View where PublisherType : Publisher, Content : View, PublisherType.Failure == Never

Overview

This view produces basically the same thing as another view with the onReceive(_:perform:) modifier applied to it. Whenever possible, use onReceive(_:perform:), as it results in cleaner code.

The following example shows SubscriptionView used to exactly reproduce a view with onReceive(_:perform:).

struct TimerView: View {
    @State private var time1 = ""
    @State private var time2 = ""

    let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()

    var body: some View {
        VStack {
            SubscriptionView(content: Text(time1), publisher: timer) { t in
                time1 = String(describing: t)
            }
            Text(time2).onReceive(timer) { t in
                time2 = String(describing: t)
            }
        }
    }
}
A gif displaying two identical timers in a VStack, the first rendered with SubscriptionView and the second with onReceive. The timers read as "2021-03-30 00:06:11 +0000".

Availability

iOS 13.0+

macOS 10.15+

tvOS 13.0+

watchOS 6.0+

Topics


Type Alias

Body The type of view representing the body of this view.


Instance Property

action The Action executed when publisher emits an event.

content The content view.

publisher The Publisher that is being subscribed.


Initializer

init(content:publisher:action:) Create a view with content that subscribes to a publisher with an action.