I see in the webs-service
reference that the message
object has a cancel
method to notify a subscribed call that no more responses will be sent (see link). When I call this method, I see the following error:
So, here a few questions:
- If I want to keep only one active subscription to a service, is it necessary to cancel the previous one?
- Can the subscriptions be called from the service side instead of the Webapp side?
- Is this the correct way to cancel subscriptions?
To simplify the understanding of the problem, I created a modified version of the HelloWorldService that consistently reproduces the issue.
- Webapp code: The only change is the addition of the
subscribe: true
on the service request.
function displayReponse() {
var value = document.getElementById("input").value;
webOS.service.request("luna://com.sample.helloworld.service/", {
method: "hello",
subscribe: true,
parameters: { name: value },
onFailure: showFailure,
onSuccess: showSuccess,
});
}
function showSuccess(res) {
document.getElementById("result1").innerHTML = "Service Responded!";
document.getElementById("result2").innerHTML = res.data;
}
function showFailure(err) {
document.getElementById("result1").innerHTML = "Failed!";
document.getElementById("result2").innerHTML =
"(" + err.errorCode + ") " + err.errorText;
console.log(err);
}
- Service code: I implemented a timer here that sends responses to the subscribed message every second. If a new call to the method comes in, it attempts to replace the subscription causing the error.
var pkgInfo = require("./package.json");
var Service = require("webos-service");
var service = new Service(pkgInfo.name);
var name = "World";
var subscription = null;
var interval = null;
var count = 0;
var hello = service.register("hello");
hello.on("request", function (message) {
console.log("In hello callback");
if (message.payload && message.payload.name) {
name = message.payload.name;
}
// First, cancel the previous subscription and clear the interval
if (subscription) {
subscription.cancel(); // CRASH!!! This call causes the error!!
if (interval) {
clearInterval(interval);
}
}
// Now, save the new subscription
subscription = message;
// Create a new interval to send the message every second
interval = setInterval(function () {
subscription.respond({
returnValue: true,
data: "Hello, " + name + "! " + count,
});
count++;
}, 1000);
});
hello.on("cancel", function (message) {
console.log("In cancel callback");
subscription = null;
if (interval) {
clearInterval(interval);
}
});
IMPORTANT NOTES:
- Both, the app and the service seems to keep working despite of the error.
- The error can be reproduced on simulator. On real TV I don’t see the error on the screen.
Thanks in advance.