Platform:

Interacting with other packages via services

You might want your package to interact with another package. It’s tempting to target the other package by name and call some of its internal methods, but a much safer and more powerful way for two packages to communiate is via a versioned API called a service.

Ultimately, packages can see and inspect one another via the PackageManager instance defined at atom.packages. But services have some major upsides:

During the package activation phase, Pulsar acts as a matchmaker to providers and consumers of services — “introducing” them to one another whenever two packages match on service name and version. This introduction doesn’t happen until both packages are activated.

To provide a service, specify a providedServices field in your package.json. You should include one or more version numbers, each paired with the name of a method on your package’s main module:

{
	"providedServices": {
		"my-service": {
			"description": "Does a useful thing",
			"versions": {
				"1.2.3": "provideMyServiceV1",
				"2.3.4": "provideMyServiceV2"
			}
		}
	}
}

In your package’s main module, implement the methods named above. These methods will be called any time a package is activated that consumes their corresponding service. They should return a value that implements the service’s API.

module.exports = {
	activate() {
		// ...
	},

	provideMyServiceV1() {
		return adaptToLegacyAPI(myService);
	},

	provideMyServiceV2() {
		return myService;
	},
};

Similarly, to consume a service, specify one or more version ranges, each paired with the name of a method on the package’s main module:

{
	"consumedServices": {
		"another-service": {
			"versions": {
				"^1.2.3": "consumeAnotherServiceV1",
				">=2.3.4 <2.5": "consumeAnotherServiceV2"
			}
		}
	}
}

These methods will be called any time a package is activated that provides their corresponding service. They will receive the service object as an argument.

You will usually need to perform some kind of cleanup in the event that the package providing the service is deactivated. To do this, return a Disposable from your service-consuming method:

const { Disposable } = require("atom");

module.exports = {
	activate() {
		// ...
	},

	consumeAnotherServiceV1(service) {
		useService(adaptServiceFromLegacyAPI(service));
		return new Disposable(() => stopUsingService(service));
	},

	consumeAnotherServiceV2(service) {
		useService(service);
		return new Disposable(() => stopUsingService(service));
	},
};