Google Meet Live Share Co-Doing API 可用來同步處理會議參與者之間的任意資料。可以是應用程式依附的任何資料。
您必須將資料序列化為 Uint8Array
,才能傳輸資料。詳情請參閱 JavaScript 標準程式庫參考資料。
如果不確定如何序列化資料,請查看下方的程式碼範例。
本指南說明如何實作 Co-Doing API。
建立 CoDoingClient
首先,請透過您在開始使用期間建立的 AddonSession
建立 CoDoingClient
。
如要建立 CoDoingClient
,請呼叫 AddonSession.createCoDoingClient
方法並提供 CoDoingDelegate
。
CoDoingDelegate
是 Co-Doing API 如何在新狀態時更新您的應用程式。正常情況下,呼叫 CoDoingDelegate.onCoDoingStateChanged
方法時,應用程式會立即套用新狀態。
以下程式碼範例說明如何使用 Co-Doing API:
TypeScript
interface MyState {
someString: string;
someNumber: number;
}
/**
* Serialize/deserialize using JSON.stringify
* You can use any method you want; this is included for as an example
*/
function toBytes(state: MyState): Uint8Array {
return new TextEncoder().encode(JSON.stringify(state));
}
function fromBytes(bytes: Uint8Array): MyState {
return JSON.parse(new TextDecoder().decode(bytes)) as MyState;
}
const coDoingClient = await addonSession.createCoDoingClient({
activityTitle: "ACTIVITY_TITLE",
onCoDoingStateChanged(coDoingState: CoDoingState) {
const newState = fromBytes(coDoingState.bytes);
// This function should apply newState to your ongoing CoDoing activity
},
});
將 ACTIVITY_TITLE 替換成活動標題。
管理目前狀態
當使用者在應用程式中採取行動時,應用程式應會立即呼叫 CoDoingClient.broadcastStateUpdate
。
以下程式碼範例顯示 CoDoingClient.broadcastStateUpdate
的實作方式:
TypeScript
const myState: MyState = {
someString: "SOME_STRING",
someNumber: 0
};
document.getElementById('some-button').onClick(() => {
myState.someNumber = myState.someNumber + 1;
coDoingClient.broadcastStateUpdate({ bytes: toBytes(myState) });
});
將 SOME_STRING 替換成應用程式目前的狀態。