This commit is contained in:
2019-09-22 17:30:31 +02:00
parent 3bd83611bd
commit 530f55bc90
+23 -9
View File
@@ -43,23 +43,37 @@ rpclibrary offers a special type of call that can be used with callbacks
```typescript ```typescript
import {Backend, Frontend, Utils} from 'rpclibrary' import {Backend, Frontend, Utils} from 'rpclibrary'
const callbacks:Function[] = [] const callbacks:Map<string, Function> = new Map()
const callbackserver = new Backend.RPCServer(20000, [{
const server = new Backend.RPCServer(20000, [{
name: 'HelloWorldRPCGroup', name: 'HelloWorldRPCGroup',
exportRPCs: () => [ exportRPCs: () => [
function triggerCallbacks(message){ callbacks.forEach(cb => cb(message)) }, function triggerCallbacks(...messages){ callbacks.forEach(cb => cb.apply({}, messages)) },
{ {
name: 'subscribe', name: 'subscribe',
hook: async (callback) => {callbacks.push(callback); return Utils.makeSubResponse()} hook: async (callback) => {
const resp = Utils.makeSubResponse()
callbacks.set(resp.uuid, callback);
return resp
}
},{
name: 'unsubscribe',
call: async (uuid) => { callbacks.delete(uuid) }
} }
] ]
}]) }])
const callbackclient = new Frontend.RPCSocket(20000, 'localhost') const client = new Frontend.RPCSocket(20000, 'localhost')
callbackclient.connect().then(async () => { client.connect().then(async () => {
const r0 = await client['HelloWorldRPCGroup'].subscribe(console.log) const res = await client['HelloWorldRPCGroup'].subscribe(async (...args:any) => {
console.log(r0) console.log.apply(console, args)
await client['HelloWorldRPCGroup'].triggerCallbacks("Hello!")
/* close the callbacks once you're done */
await client['HelloWorldRPCGroup'].unsubscribe(res.uuid)
client.unhook(res.uuid)
})
await client['HelloWorldRPCGroup'].triggerCallbacks("Hello", "World", "Callbacks")
}) })
``` ```