PubSub
The PubSub plugin adds a publish/subscribe interface between the host app and Player’s content.
Usage
Add the plugin to Player:
import { Player } from "@player-ui/player";import { PubSubPlugin } from "@player-ui/pub-sub-plugin";
const pubsub = new PubSubPlugin();
const token = pubsub.subscribe("some-event", () => { // Callback});
const player = new Player({ plugins: [pubsub],});
To unsubscribe:
pubsub.unsubscribe(token);
The PubSubPlugin
provides support for handling the publish expressions in Player content at the app level. The PubSubPlugin is included by default in the Android Player, so configuring events subscriptions can be done on Player using the provided extension methods.
{ "id": "action", "type": "action", "exp": "@[ publish('some-event', {{foo.bar}}) ]@"}
val player = AndroidPlayer(context)
// extension method for subscribing to some eventval token = player.subscribe("some-event") { name: String, data: Any? -> // name of event can be used for logging // data can be any structure passed by the content, if any // handle event}
// extension method for removing a specific event subscriptionplayer.unsubscribe(token)
If your content uses the @[ publish() ]@
expression for actions, you can subscribe to these events by using the PubSubPlugin
.
CocoaPods
Add the subspec to your Podfile
pod 'PlayerUI/PubSubPlugin'
Swift Usage
let eventHandler: (String, AnyType?) -> Void = { (eventName, eventData) in // Handle event}let plugin = PubSubPlugin([("eventName", eventHandler)])
If your content uses a different name for publishing (such as publishEvent
) you can customize the expression name that the plugin uses:
let plugin = PubSubPlugin([("eventName", eventHandler)], options: PubSubPluginOptions(expressionName: "publishEvent"))
Then, just include it in your plugins
to a Player instance:
var body: some View { SwiftUIPlayer( flow: flow, plugins: [ plugin ], result: $resultBinding )}
Note: AnyType is a custom enum type to handle the arbitrary types that can be received from these events, as the data is set in your Player Content, ensure that it matches either String, [String], or [String: String].
Publish Expression
To trigger an event to be published, use the publish()
expression in Player’s content:
{ "asset": { "id": "sample", "type": "action", "exp": "@[ publish('some-event', 'some optional data') ]@"" }}