react-native-drawing
Version:
A React Native library that provides a canvas to perform drawing actions
76 lines (75 loc) • 2.59 kB
JavaScript
/**
* Data sender side of a message system
*/
export class Sender {
constructor(codec, receivedAck, answerAck, sendData) {
Object.defineProperty(this, "codec", {
enumerable: true,
configurable: true,
writable: true,
value: codec
});
Object.defineProperty(this, "receivedAck", {
enumerable: true,
configurable: true,
writable: true,
value: receivedAck
});
Object.defineProperty(this, "answerAck", {
enumerable: true,
configurable: true,
writable: true,
value: answerAck
});
Object.defineProperty(this, "sendData", {
enumerable: true,
configurable: true,
writable: true,
value: sendData
});
Object.defineProperty(this, "messageId", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "latestMessageReceived", {
enumerable: true,
configurable: true,
writable: true,
value: null
});
}
/**
* Creates ACK promises to get shared data with the current process
* while the message is being processed
* @returns - [ message-received (ACK Promise), message-answer (ACK Promise), id (to identify responses) ]
*/
createAckInterfaces() {
const id = this.messageId++;
const received = this.receivedAck.activate(id);
const messageAnswer = this.answerAck.activate(id);
return [received, messageAnswer, id];
}
/**
* Send messages to another process and get back information (answer)
* @param target - Type of the message
* @param data - Args sahred to the other process
* @returns - Answer Promise
*/
async postMessage(target, data) {
// Creating ACKs to check status
const { latestMessageReceived } = this;
const [currentMessageReceived, messageAnswer, id] = this.createAckInterfaces();
// Queuing the received promise (waiting for the latest resolution to respect sending order)
this.latestMessageReceived = currentMessageReceived;
if (latestMessageReceived !== null) {
await latestMessageReceived;
}
// Sending message
const message = { id, target, arg: data };
const encodedData = this.codec.toJSON(message);
this.sendData(encodedData);
return messageAnswer;
}
}