## Overview Let's take a deeper look at how Destinations can help you reduce implementation time and free up your user interfaces to focus on surprising and delighting your users. There's a few main conceptual types in Destinations: **Flow:** Manages the creation, appearance, and removal of Destinations as a user navigates through the app. **Destination:** Represents a distinct view in the app, and coordinates routing and requests. Generally not directly used. **State Model:** Custom objects specific to each Destination which handle view state, business logic, and responds to events sent by the view. **Provider:** Builds and configures a Destination, its view, and the state model. Used by the Flow object to present new views. **Event:** Typically represents a user interface interaction, generally used to perform a Destination presentation or an Interactor request. Events are the foundation for decoupling the UI from the actions that the user interactions should trigger. **Interactor:** Represents an object that performs some work, typically by interfacing with an API, doing background processing, or some other self-contained work. **Action:** A higher-level representation of an Interactor request. These can be used to build complex sequences of actions. ## Flow Flows manage the creation, appearance, and removal of Destinations as a user navigates through the app. They are the single source of truth for what Destinations currently exist in the ecosystem. Typically you don't interact with them directly after they've been configured. You should almost always use either the `ViewFlow` or `ControllerFlow` classes for SwiftUI and UIKit apps respectively. When creating a Flow object you supply it with a starting Destination, along with a list of Providers which can build all the supported Destination types. All Destination user interfaces which are presented will be attached from this starting Destination's interface. In the UI where you want to attach the Flow to (generally you want to do so at the root of your app's UI hierarchy), you can call `startingDestinationView()` on a `ViewFlow` (for SwiftUI apps) or `assignRoot(rootController: )` on a `ControllerFlow` (for UIKit apps) to attach the Flow's UI hierarchy to the app's interface. This SwiftUI app sketch shows how simple it is to add a Flow object. Just assign to the Flow object the Providers for the Destination types you want to support, as well as providing the starting Destination, and then attach the Flow's interface root to the app's UI. Please see the example projects for full implementations. ```swift @State var appFlow: ViewFlow? @State var hasStartedAppFlow = false func buildAppFlow() -> ViewFlow { ... let startingTabs: [TabType] = [.home, .userNotes] let startingType: DestinationType = .tabBar(tabs: startingTabs) let startingDestination = DestinationPresentation(destinationType: startingType, presentationType: .replaceCurrent, assistantType: .basic) let homeProvider = HomeProvider() let notesProvider = NotesProvider() let tabsProvider = TabsProvider() let providers: [DestinationType: any ViewDestinationProviding] = [ .home: homeProvider, .notes: notesProvider, .tabBar: tabsProvider ] return ViewFlow(destinationProviders: providers, startingDestination: startingDestination) } var body: some Scene { WindowGroup { ZStack { if hasStartedAppFlow { appFlow?.startingDestinationView() } } .onAppear(perform: { if (hasStartedAppFlow == false) { self.appFlow = buildAppFlow() self.appFlow?.start() hasStartedAppFlow = true } }) } } ``` ## Provider A Provider is responsible for providing a specific Destination to the Flow object when it requests one. When a Flow needs to present a new Destination it finds the Provider associated with the requested Destination type and calls the `buildDestination(...)` method on the Provider. The Provider should create the state model, the Destination object, the `View` or `UIViewController`, wire them together, create any Interactors and attach them to the Destination, and finally send the new Destination object back to the Flow. There are two dictionaries in a Provider – `presentationsData` and `interactorsData` – which pair configuration objects with event types and are used to configure a Destination with the interface presentations and Interactor actions it supports. Here's a simple example that creates a ViewDestination and NotesView, assigns a a state model to the view and a datasource to the Destination that will supply Note models to the UI. Note that `Destination` in this example is a typealias to NotesView.Destination which would be defined on the Provider. NotesView's `Destination` typealias actually points the definition in its `DestinationStateable` object. This object should be the source of truth for the Destination class type being used. ```swift public func buildDestination(destinationPresentations: AppDestinationConfigurations?, navigationPresentations: AppDestinationConfigurations?, configuration: DestinationPresentation, appFlow: some ViewFlowable) -> Destination? { let destination = Destination(destinationType: .notes, destinationConfigurations: destinationPresentations, navigationConfigurations: navigationPresentations, parentDestination: configuration.parentDestinationID) let state = NotesState() let view = NotesView(destination: destination, state: state) destination.assignAssociatedView(view: view) let datasource = NotesDatasource() destination.assignInteractor(datasource, to: .notes) return destination } ``` ## Interaction Flow **View → User interaction → State Model → InterfaceAction → Interaction Assistant → Flow → new Destination** One of the main responsibilities of Destinations is to handle the presentation of new views, typically triggered from a user interacting with a UI element. These Destination events are represented by `EventTypeable`-conforming enum cases which are scoped to an individual Destination. When a user interaction triggers an event you have paired to it, the view should call `handleEvent(_:content:)` on the state model, passing in the event type and an optional content type. The state model decides what to do for each event type, but typically would end by calling back to the Destination's `performAction(for:content:)` method to trigger the configured action. For a presentation, use the non-async version of `performAction`. It can throw, and the Destination method `handleThrowable` handles that for you, logging any errors to the console with the built-in Logger class. For Interactor requests, use the async version. ```swift // In a state model func handleEvent(_ type: EventType, content: ContentType?) { switch type { case .viewNote: destination?.handleThrowable { [weak destination] in try destination?.performAction(for: type, content: content) } } } ``` The `Flow` object is called by the Destination and given the action to run. When presenting a new view it will try to find an existing Destination associated with that view type, or if one is not found, builds a new one using a Destination provider assigned to its type. The Destination's interface is then presented in the view hierarchy using the presentation type assigned to the `DestinationPresentation`'s `presentationType` property. If the event type sent to the Destination via `performAction(for:content:)` instead associated with an Interactor request, the Destination retrieves the Interactor and sends the request. ## Destination A Destination represents a unique area in an app which can be navigated to by the user. In SwiftUI this is typically a fullscreen `View` object, and in UIKit it's a `UIViewController` class or subclass, but it can also contain a group of Destination objects such as a tab bar or a carousel. A Destination holds references to the UI element it's associated with, but it doesn't handle the particulars of laying out elements on the screen. Instead, the role of Destination objects in the ecosystem is to act as a coordinator – routing events between the UI, the state model, and the Flow, and managing the Destination's place in the navigation hierarchy. You will almost always use the included `ViewDestination` and `ControllerDestination` classes for SwiftUI or UIKit apps respectively. And in general, once you create your Destination object in the Provider you will not need to worry about it in the app again. There is a bidirectional connection between a Destination and its interface which is handled by a `DestinationStateable`-conforming object, as well as a bidirectional connection between a Destination and the state model, as the state model needs to both send and receive requests from the Destinations ecosystem. Typically you'll create your own class that adopts this protocol so the view can observe state properties on the state model directly. When a Destination is removed from the ecosystem, cleanup of these connections is done internally to ensure no retain cycles occur. The state object must be stored on the user interface and should be created in the initialization method, passing in its Destination and state model. ```swift @State var destinationState: NotesInterfaceState init(destination: Destination, state: NotesState) { self.destinationState = NotesInterfaceState(destination: destination, state: state) } ``` **Destinations comes with several default Destination classes to represent common UIKit and SwiftUI interface types:** ### UIKit * `ControllerDestination` can be used to represent most `UIViewController`s in your UIKit apps. * `NavigationControllerDestination` can be used as a Destination for a `UINavigationController` class. * `TabBarControllerDestination` can be used as a Destination for a `UITabBarController` class. In the associated `UITabBarController` class which conforms to the `TabBarControllerDestinationInterfacing` protocol, you should implement the `customizeTabItem(for:controller:)` method. This method passes the tab's `TabType` value you supply, along with the `UIViewController` whose `tabBarItem` should be configured for that tab. * `SwiftUIContainerDestination` can be used as a Destination for a `SwiftUIContainerController`, which allows you to host SwiftUI content within UIKit via `UIHostingController` instance. The SwiftUI content is managed by a separate `ViewFlow` contained within the `SwiftUIContainerDestination`, and Destination presentation requests for new `View`s can even be sent from UIKit-based Destinations. ### SwiftUI * `ViewDestination` can be used to represent most`View`s in your SwiftUI apps. * `NavigationViewDestination` can be used as a Destination for a `View` which contains a `NavigationStack`. For the associated `View`, conform to the `NavigatingDestinationInterfacing` protocol and assign a `DestinationNavigator` to a `navigator` State property, which will handle `navigationPath` updates. ```swift @State public var navigator: any DestinationPathNavigating = DestinationNavigator() NavigationStack(path: $navigator.navigationPath, root: { ... } ``` * `TabViewDestination` can be used as a Destination for a `View` which contains a `TabView`. For the associated `View`, conform to the `TabBarViewDestinationInterfacing` protocol, bind the `TabViewDestination`'s `selectedTab` property to the `TabView`'s `selection` parameter, and use its `activeTabs` property to create the tabs. This is an array of `TabModel` objects which contains a `type` property you supply and can use to configure the tabs. ```swift TabView(selection: $destinationState.destination.selectedTab) { ForEach($destinationState.destination.activeTabs, id: \.self) { tab in buildView(for: tab.wrappedValue) .tag(tab.wrappedValue.type.tabName) .tabItem {         Label(tab.wrappedValue.type.tabName, systemImage: tab.wrappedValue.type.imageName) } } } ``` ### ViewModifiers * `BackNavigationModifier` adds a custom back button for `View`s which hold `NavigationStack`s, used in conjunction with a `NavigatingViewDestinationable`-conforming Destination and its `NavigatingDestinationInterfacing`-conforming `View`. ```swift // Used when building a navigation View in a ViewBuilder. Creates a BackNavigationModifier. .goBackButton { // this is a NavigatingDestinationInterfacing method which requests the navigator to move to the previous Destination in the path. backToPreviousDestination(currentDestination: destinationToBuild) } ``` * `DestinationDisappearModifier` handles the removal of a Destination from the Destinations ecosystem when its associated `View` disappears from a `NavigationStack`. ```swift // Used when building a navigation View in a ViewBuilder. Creates a DestinationDisappearModifier. .onDestinationDisappear(destination: destinationToBuild, navigationDestination: destination()) ``` * `SheetPresenter` manages the presentation of SwiftUI sheets. Used in conjunction with `SheetPresentation`, this `ViewModifier` automatically enables the presentations of Destinations in sheets which are presented from the Destination this modifier is applied to. Views which support sheet presentations should implement the `SheetPresenting` protocol on their state model. See the basic SwiftUI example project for an example of sheet support. ```swift // Used on the View's body. Creates a SheetPresenter ViewModifier. .destinationSheet(presentation: stateModel.sheetPresentation) ``` ## State Model A state model is a MainActor object that conforms to the `StateModeling` protocol and houses the business logic and view state for a Destination. It is the central interface of the user interface to the Destinations framework via its `handleEvent(_:content:)` method. Where a Destination acts as a coordinator – routing events and managing presentation – the state model owns the data of the user interface, the business logic, and the requests and responses of Interactors. This separation keeps the Destination free of feature-specific logic, allows the state model to be swapped out for testing mocks or A/B variants, and gives the view a single observable object to bind properties to. For views that have no state or custom events, you can simply use the included `DefaultDestinationState` along with its wrapper object `DestinationInterfaceState`. However in most cases you will want to create your own custom state models. The state model holds the business logic and view state for the Destination, and is where you should implement lifecycle methods like `prepareForPresentation`, `prepareForAppearance(isVisible: Bool)`, and `prepareForDisappearance(wasVisible: Bool)`. **Note:** For SwiftUI these lifecycle hooks are a much more reliable way to setup and tear down state than relying on SwiftUI's `.onAppear` modifier. A state model is held within the user interface's `DestinationStateable` object and is associated with a single Destination type through its `Destination` associated type, which determines its `EventType`, `InteractorType`, and `ContentType`. A typical state model looks like this: ```swift @Observable final class NotesState: StateModeling { typealias Destination = NotesView.Destination typealias EventType = NotesView.EventType typealias InteractorType = Destination.InteractorType typealias ContentType = Destination.ContentType var destination: Destination? var items: [Note] = [] var selectedItem: Note.ID? init(destination: Destination? = nil) {     self.destination = destination     } func handleEvent(_ type: EventType, content: ContentType?) {         switch type {             case .nextButtonTapped:             Task { [weak destination] in             let apiRequest = APIRequest(.item(.get), id: 12345)             let result = await destination?.performAction(for: type, content: apiRequest)                         switch result {             case .success(let response):             ...             case .failure(let error):             ... }             }         }     } } ``` The main way to interact with the state model from your user interface is via the `handleEvent(_:content:)` method. Typically your custom state model should switch on the event type received and either handle it internally or call back to the Destination to trigger the presentation or action(s) associated with the event type. Use the throwing `performAction(for:content:)` for presentations, and the async/await `performAction(for:content:)` or `performActions(for:content:)` methods for Interactor requests and action sequences. You can even create a custom action sequence at runtime and pass it to `performActions(configuration:content:)`. Most of the lifecycle and event handling methods on `Destinationable` have matching methods on `StateModeling` which you can implement in your custom state. When the Destination receives one of these calls its default implementation forwards the call on to the state model. You can implement any of the following on your state class as needed: * `handleInteractorResult(result:for:)` and `handleAsyncInteractorResult(result:for:)` – Called when an Interactor returns a response to a request made from a call to a Destination's `performAction(for:content:)` method. If the request was successful, you can cast the `ResultData` of the content model to the ContentType you are expecting and update the state accordingly. Generally, use of this method is discouraged in favor of the more modern async/await calls that return a Result directly. * `prepareForPresentation()` – Called once when the Destination is first presented by a Flow, before its UI is built. Use this for initial state setup that should only run once. * `prepareForAppearance(isVisible: Bool)` – Called each time the Destination's UI is about to become active. The `isVisible` parameter indicates whether this Destination will actually be on-screen, which is useful for skipping setup work in the middle of a deep-link path presentation. * `prepareForDisappearance(wasVisible: Bool)` – Called each time the Destination's UI is about to become inactive. Use this for teardown tasks. * `configureInteractor(_:type:)` – Called automatically when an Interactor is assigned to the Destination. This is a good place to make any initial requests needed to setup the Interactor. * `cleanupResources()` – Called when the Destination is about to be removed from the Flow. Use this to stop in-progress Interactor tasks and release resources. The state model should be created by the Destination's Provider when its `buildDestination` method is called by the Flow. The View holds the state model in a `DestinationStateable`-conforming object. Destinations provides a generic `DestinationInterfaceState` class if your user interface needs no specific state model, however in general you will want to have a custom object for each interface in your app. This interface object is also a good place to put your `EventTypeable` and `InteractorTypeable` enum types to define the events and interactors associated with the Destination. ```swift @Observable final class NotesInterfaceState: DestinationStateable { @AutoCaseIterable     enum Events: EventTypeable { ...     } enum InteractorType: InteractorTypeable {         case notes     } typealias Destination = NavigationViewDestination var destination: Destination var stateModel: NotesState init(destination: Destination, state: NotesState) { self.destination = destination self.stateModel = state } } ``` The user interface can access the state model through this interface state object, observing properties for updates: ```swift struct NotesView: NavigatingDestinationInterfacing { <....> @State var destinationState: NotesInterfaceState init(destination: Destination, state: NotesState) { self.destinationState = NotesInterfaceState(destination: destination, state: state) } var body: some View { NavigationStack(path: $destinationState.navigator.navigationPath, root: { List(stateModel.items, selection: $destinationState.stateModel.selectedItem) { note in NotesRow(item: note) } } <....> } } ``` ### Configure a Destination To really make a Destination a first-party member of the ecosystem we need to define interface presentation and Interactor request actions on it. Once we assign these to an event type and give them to a Provider, the state model (via a user interaction or business logic) can trigger one of these actions simply by passing along the event type. #### Interface Presentations `DestinationPresentation` objects should be created to define every Destination presentation a user can initiate. These presentation objects can be reused in multiple destinations (such as presenting an error sheet or account screen), or attached to a specific Destination. There's a few main properties to configure. * The `destinationType` property represents the type of Destination to be presented. This should be a value of an enum type of your choosing. Multiple presentations may use the same type. For instance, you could have a `.userProfile` type that is represented in two different `DestinationPresentation`s – presented in your app both in a Profile tab and also appearing in a sheet. This property is optional, but if you intend to display a new Destination then you'll need to define one. * The `presentationType` property denotes how a Destination's interface should be presented in the UI, such as in a navigation stack or a sheet. Several types are available that represent system navigation type as well as custom behaviors. More information on each type is available in the [DestinationPresentation](#destinationpresentation) section. * The `contentType` property allows you to pass in a content model to supply configuration data or initial data for the Destination's interface. * The `assistantType` property allows you to define an assistant which provides additional configuration when the Destination is being presented. In the majority of cases you can just use the `.basic` assistant which Destinations implements internally. Destinations has several built-in presentation types which `DestinationPresentation` supports to enable native SwiftUI and UIKit UI navigation, as well as more complex or custom behavior. * **`navigationStack(type: NavigationPresentationType)`** This presentation type will add and present a Destination in a navigation stack such as SwiftUI's `NavigationStack` or UIKit's `UINavigationController`. * **`tabBar(tab: TabType)`** This presentation type will present a Destination in the specified tab of a tab bar component, such as SwiftUI's `TabView` or UIKit's `UITabBarController`. If no `destinationType` is present in the `DestinationPresentation` model, the specified tab will simply be selected, becoming the active tab within the interface. * **`splitView(column: SplitViewColumn)`** This presentation type will present a Destination in a column of a split view interface, such as a `UISplitViewController` or SwiftUI's `NavigationSplitView`. The `column` parameter defines the column of the split view to present the Destination in. * **`addToCurrent`** This presentation type adds a Destination as a child of the currently-presented Destination. Note that this type only works with UIKit and utilizes `UIViewController`'s `addChild` method. * **`replaceCurrent`** This presentation type replaces the currently-presented Destination with a new Destination in system UI components which allow that. * **`replaceRoot`** This presentation type removes all active Destinations in the Flow and sets a new root Destination. This is useful in use cases such as a user signing out, where you need to remove all the current UI and present a new screen. * **`moveToNearest`** This presentation type finds the nearest Destination of the specified type in the view hierarchy and makes it the current Destination, starting from the current Destination and moving upwards in the hierarchy. Typically this presentation type would be used to move to another Destination's user interface higher in a navigation stack. The target Destination type is specified via the `destinationType` property of the associated ``DestinationPresentation`` model and is required. * **`sheet(type: SheetPresentationType, options: SheetPresentationOptions?)`** This presentation type presents (or dismisses) a Destination in a sheet. The `options` parameter allows you to customize how the sheet is presented, configuring SwiftUI-specific options with a `ViewSheetPresentationOptions` model and UIKit-specific options with a `ControllerSheetPresentationOptions` model. * **`destinationPath(path: [DestinationPresentation])`** This presentation type presents a path of multiple Destination objects, useful for providing deep linking functionality or building complex state with one user interaction. Note that the `destinationPath` presentation type will automatically disable the navigation stack presentation animations of all of its Destination presentations to better support deep linking use cases. This default behavior can be overriden by adding a `NavigationStackPresentationOptions` model with its `shouldAnimate` property set to true for each `DestinationPresentation` you want to change. * **`custom(presentation: CustomPresentation)`** This presentation type enables you to present a custom presentation of a Destination. It can be used to support the presentation of custom UI, as well as system components which Destinations does not directly support. The `presentation` parameter allows you to use a `CustomPresentation` model with specialized closures to provide whatever functionality you need. #### Interactor requests For Interactor requests, use `InteractorConfiguration` objects to define actions which can be requested from UI interactions. * The `interactorType` property defines the type of Interactor to request an action from. The association between a specific Interactor and an interactor type is made when calling the `assignInteractor(_:to:)` method on a Destination. * The `actionType` property defines the specific action of the interactor to be requested, represented by an enum type of your choosing and is scoped to individual Interactors. * The `assistantType` property allows you to define an assistant which handles requests and responses to its Interactor. You can also supply more complex action sequences with `ActionSequenceConfiguration` or `ActionGroupConfiguration`. They both conform to `InteractorConfiguring` as `InteractorConfiguration` does so they can be assigned to an Event in the same way. These `DestinationPresentation`s and `InteractorConfiguration` objects are assigned to a specific Event type in the `presentationsData` and `interactorsData` dictionaries respectively. ```swift struct NotesListProvider: ViewDestinationProviding {     typealias Destination = NotesView.Destination typealias TabType = Destination.TabType typealias ContentType = Destination.ContentType     var presentationsData: [Destination.EventType: DestinationPresentation] = [:]     var interactorsData: [Destination.EventType : any InteractorConfiguring] = [:]     init() { // presentations         let noteSelection = DestinationPresentation( destinationType: .noteDetail, presentationType: .navigationStack(type: .present), assistantType: .basic)         presentationsData = [.noteButton: noteSelection] // interactor requests let listAction = InteractorConfiguration( interactorType: .notes, actionType: .list, assistantType: .custom(NotesAssistant())) let addNoteAction = InteractorConfiguration( interactorType: .notes, actionType: .addNote, assistantType: .custom(NotesAssistant())) interactorsData = [.initialRetrieval: listAction, .tapNewNoteButton: addNoteAction]     } <.....> } ``` ## Interactor The concept of Interactors comes from [Clean Swift](https://clean-swift.com), used in its architecture as a way to move logic and datasource management out of view controllers. In Destinations, the `Interactable` and `AsyncInteractable` protocols represents Interactor objects which provide an interface to perform some task or data request, typically by interfacing with an backend API, interfacing with system frameworks, or some other self-contained work. Though requests to Interactors can be made using a Destination's `performRequest` method, in general one should use the Destination's `performAction(for:content:)` method. This abstracts the specific implementation details of an interactor away from the interface and lets it focus on making requests through a standardized request. The recommended way is to assign an event type to your request and using an `InteractorAssisting`-conforming assistant to configure the request, leaving the Destination's interface free of associated business logic. Interactors should be created by Providers and attached to the Destination when created with an associated interactor enum type. Like with interface presentation actions, Interactor requests are associated with a particular `InterfaceAction` object and are represented by an `InteractorConfiguration` model object, which is all stored in the Destination. Action types for each Interactor are defined as enums, keeping Interactor-specific knowledge out of the interface. For example, here we're creating an Interactor action for making a pagination request to the NotesDatasource and associating the action to a `moreButton` event type. ```swift let paginateAction = InteractorConfiguration( interactorType: .notes, actionType: .paginate, assistantType: .custom(NotesAssistant())) let notesProvider = NotesProvider(interactorsData: [.moreButton: paginateAction]) ``` As with interface presentation events, Interactor requests are typically made by having the state model call the `performAction(for:content:)` method on the Destination and sending the event type associated with the interactor request. ### Interactor assistants Interactor assistants are conduits between a Destination and its Interactors, mainly used in conjunction with the `performAction(for:content:)` method. They create the actual Request model to be passed to the Interactor based on the interface action type passed to it, and for async assistants they also pass on the result of the Interactor's operation to the Destination. They are defined when creating an `InteractorConfiguration` and there are four types: `basic`, `basicAsync`, `transformer(request:result:)`, and `custom(assistant:)`. The `basic` and `basicAsync` types represent built-in assistants to be used with synchronous and async Interactors respectively.  If the content state passed in with a request is the same type as the Request's `ResultData` type, these assistant types are all you need. If you need to pass in content with the request, this type can also handle that automatically if the content's type is the same as the Request's `RequestContentType`. Otherwise, you will need to use a `transformer` assistant type which bridges request and result content types using the given transformers when the Interactor's `Request.RequestContentType`/`Request.ResultData` differ from the Destination's `ContentType`. Only in cases where you need to supply custom logic or dynamic content state handling would you need to use the `custom` type with a custom assistant. #### Bridging content types with `transformer` If an async Interactor's `Request.RequestContentType` or `Request.ResultData` differ from the Destination's `ContentType`, you can use the `transformer(request:result:)` assistant type and supply `ContentTransformable` objects to do the conversion for you. These are the same transformer types that are used with ActionSequences, and can be used interchangeably. * `request` converts the Destination's `ContentType` into the Request's `RequestContentType` before a request is made. Pass `nil` if the Interactor doesn't need any content passed in, or if the two types are already the same. * `result` converts the Interactor's `Request.ResultData` into the Destination's `ContentType` after the request completes. Pass `nil` if the two types are already the same. Passing `nil` for both is valid, but is equivalent to just using `basicAsync`. ```swift struct ColorsRequestTransformer: ContentTransformable { func transform(input: AppContentType) throws -> ColorsRequestContent { if case .colorsRequest(requestModel: let model) = input { return model } return .numColorsToRetrieve(3) } } struct ColorsResultTransformer: ContentTransformable { func transform(input: ColorsResult) throws -> AppContentType { switch input { case .retrievedColors(let models): return .colors(models: models) } } } ``` Destination classes can make async requests of an Interactor assistant through the `asyncRequest(destination:, actionType:, content:)` method and receive the Interactor's Result directly. Custom assistants should create a Request object with the provided action type and any other configuration state, call `performRequest(...)` on the Interactor, and then pass back the result to the Destination. The Destination then forwards this on to the state model. You might also want to use a custom assistant to handle an Interactor which returns an ongoing sequence of values, for instance listening to Core Location updates or consuming updates from a real-time server subscription. You can see an example of this with the Counter tab in the SwiftUI basic example project, which consumes values from an AsyncStream. Here's an example custom assistant implementation of `handleAsyncRequest()` where we're requesting the Interactor to add a Note. The Note model is passed via the `content` parameter and then added to the action type, which the assistant then passes in with the NoteRequest to the Interactor. After the operation is complete, the result is passed back and sent on to the Destination via the `handleAsyncInteractorResult()` method. ```swift func handleAsyncRequest(destination: Destination, actionType: Request.ActionType, content: ContentType?) async where Destination.InteractorType == InteractorType { switch actionType { case .add: switch content { case .note(model: let note): let request = NoteRequest(action: .add(note: note)) let result = await destination.performRequest(interactor: interactorType, request: request) await destination.handleInteractorResult(result: result, for: request) default: break } } } ``` ### Handling an Interactor result We've shown how to connect an Interactor action to an event request, but how do we handle the result of the operation? When using an Interactor that conforms to `AsyncInteractable` and making a request via the Destination's `performAction(for:content:)` method, the Result is passed back directly via an await. If you are using a non-async Interactor, you can use the non-async version of `performAction(for:content:)` and receive the result via the state model's `handleAsyncInteractorResult` method and then cast the response's `ResultData`. ```swift // In a state model Task { let result = await destination?.performAction(for: .retrieveNotes, content: content) switch result { case .success(let response): switch response as? NotesRequest.ResultData { case .notes(models: let notes): self.items = notes default: break } case .failure(let error): destination?.logError(error: error) } } ``` If you wish to forego passing off requests to the Destination (and thus bypassing the assistant as well) and instead deal directly with an Interactor, such as using a TaskGroup to make multiple requests, you can access the Interactor from the Destination. Making requests of the interactor this way allows you to directly access the request's `ResultData` type in the response, but at the cost of a loss of abstraction of implementation details. ```swift guard let interactor = destination?.interactor(for: .notes) as? any AsyncInteractable else { return } Task { let result = await interactor.perform(request: NotesRequest(action: .retrieve)) switch result { case .success(let response): ... } } ``` ## Action Sequences For workflows that involve more than one Interactor request, Destinations provides Action Sequences. They're a powerful way to encapsulate a complex series of async Interactor requests and perform them as a single action which participates in Swift's async/await concurrency environment. Instead of instantiating Action Sequence classes directly, you build the sequence types declaratively using configuration object chains. There are four main building blocks when assembling a sequence configuration: **`ActionConfiguration`**: A step that handles a single Interactor action type. **`ActionSequenceConfiguration`**: An ordered pipeline of steps that run one after the other. **`ActionGroupConfiguration`**: An action collection that runs multiple child actions concurrently, then merges their results into one value. **`ActionBranchConfiguration`**: A special branching type that evaluates conditions at runtime and runs the first matching path. Here's a minimal example of a two-step sequence that retrieves notes and then saves them. ```swift let retrieveNotesAction = ActionConfiguration( interactorType: .notes, action: .retrieve, assistant: .basicAsync, identifier: StepType.retrieve) let saveNotesAction = ActionConfiguration( interactorType: .notes, action: .save, assistant: .custom(NotesSaveAssistant()), identifier: StepType.save) let sequence = ActionSequenceConfiguration() .step(retrieveNotesAction) .step(saveNotesAction, inputTransformer: NotesTransformer()) let result = await destination.performActions(configuration: sequence) ``` Each step automatically creates an output conduit that forwards the preceding step's output content to the next step. You can also supply an optional transformer to transform the incoming content if the two steps have different content shapes. For a full walkthrough covering groups, branching, conditions, result handling, and cancellation, see the **[Action Sequence Guide](ActionSequenceGuide.md)**. Please also see the [ActionSequence](../Examples/SwiftUI/ActionSequence/) example project. ## Next Steps Now that you've had an overview of the major concepts in Destinations, please check out the [Examples projects](../Examples/) to see Destinations in action in UIKit and SwiftUI, or dive deep into the source [Documentation](https://poetmountain.github.io/Destinations/).