Skip to main content

General principles

Deferred results​

Some SDK methods, such as directory or routing requests, return a deferred result Future<T>. To process it, keep a reference to Future until the operation is complete and subscribe using onComplete().

You can call destroy() to explicitly release native resources early, for example, after receiving a result or when unmounting a screen. This step is optional for SDK objects, but it is useful for long-running operations and screens that frequently create requests.

Example of getting an object from the directory:

import { useEffect, useMemo, useRef, useState } from 'react';
import {
SearchManager,
type Context,
type DirectoryObject,
type Future,
} from '@2gis/dgis-mobile-sdk-full';

function useDirectoryObject(context: Context, id: string) {
const searchManager = useMemo(
() => SearchManager.createOnlineManager(context),
[context],
);
const futureRef = useRef<Future<DirectoryObject | null> | null>(null);
const [object, setObject] = useState<DirectoryObject | null>(null);

useEffect(() => {
return () => searchManager.destroy();
}, [searchManager]);

useEffect(() => {
const future = searchManager.searchById(id);
futureRef.current = future;

future.onComplete(
result => {
future.destroy();
futureRef.current = null;
setObject(result);
},
error => {
future.destroy();
futureRef.current = null;
console.warn(error);
},
);

return () => {
futureRef.current?.destroy();
futureRef.current = null;
};
}, [id, searchManager]);

return object;
}

For more information on working with the directory, see the Directory section.

Data channels​

Some SDK objects provide data channels. Use Channel.subscribe() to subscribe to a channel and Connection.disconnect() to unsubscribe. Keep a reference to Connection while the subscription is active. If the reference is lost, the garbage collector may delete the JavaScript object and disconnect the subscription. For more information, see the Connection class description.

Example of subscribing to camera parameter changes:

import { useEffect } from 'react';
import type { Map } from '@2gis/dgis-mobile-sdk-full';

function useCameraChanges(map: Map | null) {
useEffect(() => {
if (map === null) {
return;
}

const connection = map.camera.changed.subscribe(change => {
console.log('Camera changed:', change);
});

return () => {
connection.disconnect();
};
}, [map]);
}

If the channel is a StatefulChannel<T>, its current value is immediately available through value:

const currentPosition = map.camera.position;
const currentLoadingState = map.dataLoadingStateChannel.value;