Loading resources asynchronously

Resources such as layers, maps, portal items, tasks, and so on, commonly rely on remote services or datasets on disk to initialize their state. The nature of accessing such data requires the resources to initialize their state asynchronously. The loadable design pattern unifies the behavior that different resources use to load metadata asynchronously. Resources that adopt this pattern are referred to as "loadable." The pattern also provides a mechanism to retry if previous attempts to load failed so that you can properly handle and recover from exceptional circumstances such as network outages or service interruption. Loadable resources appropriately handle concurrent and repeated requests to load in order to accommodate the common practice of sharing the same resource instance among various parts of an application. They also permit cancellation so that you can cancel loading a resource, for example, if the service is slow to respond. Finally, loadable resources provide information about their initialization status through explicit states that can be inspected and monitored.

Classes that conform to the loadable pattern adopt the Loadable protocol.

Load status

The LoadStatus is the state of the loadable resource. Four states are possible.

  • notLoaded—the resource has not been asked to load its metadata and its state isn't properly initialized yet.
  • loading—the resource is in the process of loading its metadata asynchronously.
  • failed—the resource failed to load its metadata (for example, due to network outage, or the operation was cancelled, and so on.) The error encountered is available in the loadError property.
  • loaded—the resource successfully loaded its metadata and its state is properly initialized.

The following state transitions represent the stages that a loadable resource goes through.

Loadable flow diagram

loadStatus is a streamed property. The Streamed property wrapper uses an async sequence that emits a value when the wrapped property value changes. This makes it easy to monitor the status of loadable resources, display progress, and take action when the state changes.

Loading

A resource starts loading its metadata asynchronously when load() is invoked either through an explicit call or when another object requires that the resource is loaded. For example, Map.load() will be invoked by MapView in preparation for displaying a map. At that time, the load status changes from notLoaded to loading. If the operation completes successfully, the loadError property is nil and the load status is set to loaded, which means the resource has finished loading its metadata and is now properly initialized. If the operation encounters an error, the loadError property is populated, and load status is set to failed.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct ContentView: View {
    @State private var map = Map(basemapStyle: .arcGISImageryStandard)

    var body: some View {
        MapView(map: map)
            .task {
                for await loadStatus in map.$loadStatus {
                    print(loadStatus.title)
                }
            }
    }
}

private extension LoadStatus {
    /// Extends LoadStatus to provide a human readable title.
    var title: String {
        switch self {
        case .notLoaded: "Not Loaded"
        case .loading: "Loading"
        case .loaded: "Loaded"
        case .failed: "Failed"
        }
    }
}

Many times, the same resource instance is shared by different parts of the application. For example, a legend component and a table of contents component may have access to the same layer, and they both may want to access the layer's properties to populate their UI. Or the same portal instance may be shared across the application to display the user's items and groups in different parts of the application.

In order to accommodate this type of application development pattern, you can check the load status of any resource at any point in your app. load() can be called concurrently and repeatedly, but only one attempt is ever made to load the metadata. If a load operation is already in progress (loading state) when load() is called, it simply piggy-backs on the outstanding operation. This makes it safe for you to liberally invoke load() on a loadable resource, without having to check if the resource is already loaded or not, and without worrying that it will make unnecessary network requests every time.

If a resource has failed to load, calling load() on it subsequently will not change its state. The async call will return immediately with the past load error. In order to retry loading the resource, you must use retryLoad() instead. The advantage of this approach is that if, hypothetically, load() were to retry loading a failed resource, an app could easily end up making many asynchronous requests to load the same resource just because it shared the same resource instance in different parts of the application and each part tried to load the resource without first checking if it was already loading. This pattern allows load() to be invoked indiscriminately without worrying that it might add overhead, and makes retrying a separate and explicit scenario using retryLoad().

Retry loading

A resource retries to load its metadata when retryLoad() is invoked, but only if it previously failed to load (failed state) or wasn't loaded to begin with (notLoaded state). The resource transitions to the loading state and makes a new attempt to fetch its metadata.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
var body: some View {
    MapView(map: map)
        .task {
            for await loadStatus in map.$loadStatus where loadStatus == .failed {
                do {
                    try await map.retryLoad()
                } catch {
                    print(error)
                }
            }
        }
}

If the resource has already fetched its metadata and has initialized its state (loaded state), retryLoad() doesn't do anything and the load state remains unchanged. The object's metadata isn't fetched again.

If an asynchronous operation is already in progress (loading state) when retryLoad() is called, it simply piggy-backs on the outstanding operation and the callback is enqueued to be invoked when that operation completes.

The main use case for this method is when the loadable resource failed to load previously, for example, due to network outage or service interruption. It is not meant to refresh the metadata for an already loaded resource which can instead be accomplished by creating a new instance of the loadable resource.

Cancel loading

A resource cancels any outstanding asynchronous operation to load its metadata when cancelLoad() is invoked and it transitions from loading to failed state. The retryLoad() information that reflects that operation is cancelled.

This method should be used carefully because all enqueued callbacks for that resource instance will get invoked with an error stating that the operation was cancelled. Thus, one component in the application can cancel the load initiated by other components when sharing the same resource instance.

The cancelLoad() method does nothing if the resource is not in loading state.

Conveniences

Cascade load dependencies

It is common for a loadable resource to depend on loading other loadable resources to properly initialize its state. For example, a portal item cannot finish loading until its parent portal finishes loading. A feature layer cannot be loaded until its feature service table is first loaded. This situation is referred to as a load dependency.

Loadable operations invoked on any resource transparently cascade through its dependency graph. This makes using loadable resources simple and puts the responsibility on the resource to correctly establish and manage its load dependencies.

Cascading behavior leads to concise code. Loading the map causes the portal item to begin loading, which in turn initiates loading its portal. You do not have to load each one of them explicitly.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Creates the portal item found in the ArcGIS Online portal
let portalItem = PortalItem(
    portal: .arcGISOnline(connection: .anonymous),
    id: PortalItem.ID("acc027394bc84c2fb04d1ed317aac674")!
)

// Creates the map
let map = Map(item: portalItem)

// Loads the map and catches any errors
do {
    try await map.load()
} catch {
    print(error)
}

It is possible that dependencies may fail to load. Some dependencies might be critical without which the initiating resource cannot load successfully, for example, a portal item's dependency on its portal. If a failure is encountered while loading such a dependency, that error would bubble up to the resource that initiated the load cycle, which would also fail to load. Furthermore, retrying to load that resource would automatically retry loading the failed dependency. Other load dependencies may be incidental, such as a map's dependency on one of its operational layers, and the resource may be able to load successfully even if one of its dependency fails to load.

Override state before initialization

A loadable resource's state is not properly initialized until it has finished loading. Accessing properties of the resource before the resource is loaded could return nil or uninitialized values that might change when the resource finishes loading. Therefore, it is always advisable to wait until the resource has finished loading before accessing its properties. However, many times, especially while prototyping, you may want to change a property value before the resource is loaded without regard for its proper initialized value. For instance, you may want to change the scale visibility of a layer or the initial viewpoint of a map. To simplify this workflow without requiring that the resource first be loaded, loadable resources permit overriding their properties before the resource has finished loading and the overridden value will take precedence over the value specified in the resource's metadata.

For example, you can override the min/max scale properties of a layer without having to load it first.

Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
// Creates an ArcGIS map image layer and sets the min/max scale
let layer = ArcGISMapImageLayer(url: URL(string: "https://sampleserver5.arcgisonline.com/arcgis/rest/services/Census/MapServer")!)
layer.minScale = 10_000_000
layer.maxScale = 100_000

// Loads the layer and catch any errors
do {
    try await layer.load()
} catch {
    print(error)
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.