Toggle between feature request modes

View on GitHubSample viewer app

Use different feature request modes to populate the map from a service feature table.

Toggle between feature request modes

Use case

Feature tables can be initialized with a feature request mode which controls how frequently features are requested and locally cached in response to panning, zooming, selecting, or querying. The feature request mode affects performance and should be chosen based on considerations such as how often the data is expected to change or how often changes in the data should be reflected to the user.

  • ON_INTERACTION_CACHE - fetches features within the current extent when needed (after a pan or zoom action) from the server and caches those features in a table on the client. Queries will be performed locally if the features are present, otherwise they will be requested from the server. This mode minimizes requests to the server and is useful for large batches of features which will change infrequently.

  • ON_INTERACTION_NO_CACHE - always fetches features from the server and doesn't cache any features on the client. This mode is best for features that may change often on the server or whose changes need to always be visible.

    NOTE: No cache does not guarantee that features won't be cached locally. Feature request mode is a performance concept unrelated to data security.

  • MANUAL_CACHE - only fetches features when explicitly populated from a query. This mode is best for features that change minimally or when it is not critical for the user to see the latest changes.

How to use the sample

Choose a request mode by clicking on a radio button. Pan and zoom to see how the features update at different scales. If you choose "Manual cache", click the "Populate" button to manually get a cache with a subset of features.

Note: The service limits requests to 2000 features.

How it works

  1. Create a ServiceFeatureTable with a feature service URL.
  2. Set the FeatureRequestMode property of the service feature table to the desired mode (ON_INTERACTION_CACHE, ON_INTERACTION_NO_CACHE, or MANUAL_CACHE).
    • If using MANUAL_CACHE, populate the features with ServiceFeatureTable.populateFromServiceAsync().
  3. Create a FeatureLayer with the feature table and add it to an ArcGISMap's operational layers to display it.

Relevant API

  • FeatureLayer
  • ServiceFeatureTable
  • ServiceFeatureTable.FeatureRequestMode

About the data

This sample uses the Trees of Portland service showcasing over 200,000 street trees in Portland, OR. Each tree point models the health of the tree (green - better, red - worse) as well as the diameter of its trunk.

Tags

cache, data, feature, feature request mode, performance

Sample Code

MainActivity.kt
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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/* Copyright 2022 Esri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.esri.arcgisruntime.sample.togglebetweenfeaturerequestmodes

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.QueryParameters
import com.esri.arcgisruntime.data.ServiceFeatureTable
import com.esri.arcgisruntime.data.ServiceFeatureTable.FeatureRequestMode
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.togglebetweenfeaturerequestmodes.databinding.ActivityMainBinding
import java.util.Collections
import java.util.concurrent.atomic.AtomicInteger


class MainActivity : AppCompatActivity() {

    private val TAG: String = MainActivity::class.java.simpleName

    private val activityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val mapView: MapView by lazy {
        activityMainBinding.mapView
    }

    private val modeButton: Button by lazy {
        activityMainBinding.mode
    }

    private val populateButton: Button by lazy {
        activityMainBinding.populate
    }

    private val progressBar: ProgressBar by lazy {
        activityMainBinding.progressBar
    }

    private val labelTV: TextView by lazy {
        activityMainBinding.labelText
    }

    // instance of the FeatureLayer to be used by the map
    private var featureLayer: FeatureLayer? = null

    // currently selected feature mode: 0.Cache, 1.No cache, 2.Manual cache
    private var featureModeSelected: Int = 0

    // instance of the service feature table of street trees in Portland
    private var featureTable: ServiceFeatureTable? =
        ServiceFeatureTable("https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/rest/services/Trees_of_Portland/FeatureServer/0")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activityMainBinding.root)

        // authentication with an API key or named user is
        // required to access basemaps and other location services
        ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)

        mapView.apply {
            // set the map to be displayed in the layout's MapView
            map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC)
            // set the starting viewpoint for the map view
            setViewpoint(Viewpoint(45.5266, -122.6219, 6000.0))
        }
        // create a feature layer from the service feature table
        featureLayer = FeatureLayer(featureTable)
        // set up the UI for switching between request modes
        setUpUi()
    }

    /**
     * Sets up the listeners for the UI when Mode or Populate views are clicked
     */
    private fun setUpUi() {
        // display feature mode options when the mode view is clicked
        modeButton.setOnClickListener {
            val featureModeChoices = arrayOf("Cache", "No cache", "Manual cache")
            // create an alert dialog and set up the options
            val alertDialog: AlertDialog.Builder = AlertDialog.Builder(this@MainActivity).apply {
                setTitle("Choose a feature request mode")
                setSingleChoiceItems(
                    featureModeChoices, featureModeSelected
                ) { dialog, which ->
                    dialog.dismiss()
                    // update and set the current feature mode selected
                    featureModeSelected = which
                    setUpFeatureMode()
                }
            }
            // Displays the dialog
            val alert: AlertDialog = alertDialog.create()
            alert.setCancelable(false)
            alert.show()
        }
        // fetch cache manually when the populate button is clicked
        populateButton.setOnClickListener {
            fetchCacheManually()
        }
        // set label text on app launch
        labelTV.text = getString(R.string.labelDefaultText)
    }

    /**
     * Sets up the [featureLayer] to the [mapView] and updates the layer
     * to the selected feature request mode
     */
    private fun setUpFeatureMode() {
        // check if the feature layer has already been added to the map's operational layers, and if not, add it
        mapView.map.apply {
            if (operationalLayers.isEmpty()) {
                operationalLayers.add(featureLayer)
            }
        }
        // check the feature layer has loaded before setting the request mode of the feature table, selected from
        // the radio button's user data
        featureLayer?.addDoneLoadingListener {
            if (featureLayer?.loadStatus == LoadStatus.LOADED) {
                // set request mode of service feature table to selected toggle option
                featureTable?.featureRequestMode = getSelectedMode()
            } else {
                val error = "FeatureLayer failed to load" + featureLayer?.loadError?.message
                Toast.makeText(this, error, Toast.LENGTH_SHORT).show()
                Log.e(TAG, error)
            }
        }
    }

    /**
     * Fetches the cache from a Service Feature Table manually.
     */
    private fun fetchCacheManually() {
        // show loading ProgressBar when fetching manually
        progressBar.visibility = View.VISIBLE
        // create query to select all tree features
        val queryParams = QueryParameters().apply {
            // query for all tree conditions except "dead" with coded value '4' within the visible extent
            whereClause = "Condition < '4'"
            geometry = mapView.visibleArea.extent
        }

        // * means all features
        val outfields: List<String> = Collections.singletonList("*")

        // get queried features from service feature table and clear previous cache
        val tableResult = featureTable?.populateFromServiceAsync(queryParams, true, outfields)
        tableResult?.addDoneListener {
            try {
                // find the number of features returned from query
                val featuresReturned = AtomicInteger()
                tableResult.get().forEach { _ -> featuresReturned.getAndIncrement() }
                // display number of returned features to the user
                // note the service has a maximum record count of 2000
                labelTV.text = "Populated $featuresReturned features."
                // hide the loading ProgressBar
                progressBar.visibility = View.GONE
            } catch (e: Exception) {
                val error = "PopulateFromServiceAsync failed to load" + e.message
                Toast.makeText(this, error, Toast.LENGTH_SHORT).show()
                Log.e(TAG, error)
                // hide the loading ProgressBar
                progressBar.visibility = View.GONE
            }
        }
    }

    /**
     * Updates the [labelTV] text and returns the selected
     * FeatureRequestMode using [featureModeSelected]
     */
    private fun getSelectedMode(): FeatureRequestMode {
        // enable populate view if request mode is manual cache
        populateButton.isEnabled = featureModeSelected == 2
        when (featureModeSelected) {
            0 -> {
                labelTV.text = getString(R.string.cacheEnabled)
                return FeatureRequestMode.ON_INTERACTION_CACHE
            }
            1 -> {
                labelTV.text = getString(R.string.noCacheEnabled)
                return FeatureRequestMode.ON_INTERACTION_NO_CACHE
            }
            2 -> {
                labelTV.text = getString(R.string.manualCacheEnabled)
                return FeatureRequestMode.MANUAL_CACHE
            }
        }
        return FeatureRequestMode.MANUAL_CACHE
    }

    override fun onPause() {
        mapView.pause()
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        mapView.resume()
    }

    override fun onDestroy() {
        mapView.dispose()
        super.onDestroy()
    }
}

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