I'm trying to interact with a JS api, once a video is loaded/fails to load/is viewed I'd like to send back an event using EventSystem. I got the first part working, where I call the native JS apis:
@JsType(namespace = JsPackage.GLOBAL, name = "ApiRequestHandler", isNative = true)
public class ApiRequestHandler {
public native void loadVideo();
public native void showVideo();
}
ApiRequestHandler= function () {
var preloadedVideo = null;
}
ApiRequestHandler.prototype.loadVideo = function () {
Api.getVideoAsync().then(function(video) {
// Load asynchronously
preloadedVideo = video;
return preloadedVideo.loadAsync();
}).then(function() {
console.log('Video preloaded');
}).catch(function(err){
console.error('Video failed to preload: ' + err.message);
});
}
ApiRequestHandler.prototype.showVideo = function () {
preloadedVideo.showAsync()
.then(function() {
// Perform post-ad success operation
console.log('Video watched successfully');
})
.catch(function(e) {
console.error(e.message);
});
}
My problem is with calling Java objects from JS, I came with a response handler class, which has a dependency on EventSystem. How can I initialize the EventSystem in this class, but then let JS promise resolution call sendEvent? (to make this clear, the above JS code console calls, need to instead call the eventSystem, to report back success or error).
@JsType(isNative = true)
public class ApiResponseHandler {
EventSystem eventSystem;
public void sendEvent(int msg) {
final Event event = new Event();
event.message = msg;
eventSystem.dispatch(event);
}
@JsOverlay
public void setEventSystem(EventSystem eventSystem) {
this.eventSystem = eventSystem;
}
}
I came with a solution, but I'm not sure if it is optimal, so I'll leave the question if someone has a better one.
First, an interface with a single method, which serves as a callback function in JS 'world'
I actually included another interface for fail callbacks, the only difference is the method takes String of the error:
void call(String error)Then the ApiRequestHandler changes to:
I have a wrapper class for this object, that simply calls the native JS functions, but also provides implementation for callbacks (in form of a lambda) and has a reference to EventSystem, so I can send my events from the callback:
Finally, the changes to JS code: