Skip to content

Commit

Permalink
Add named callbacks to the js promise construct
Browse files Browse the repository at this point in the history
(used for async communication which needs to callback many different times before the promise resolves)
  • Loading branch information
MarmadileManteater committed Mar 22, 2024
1 parent ceae748 commit c92fd7d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,15 @@ class FreeTubeJavaScriptInterface {
syncMessages.remove(promise)
return value!!
}
private fun addNamedCallbackToPromise(promise: String, name: String) {
context.runOnUiThread {
context.webView.loadUrl("javascript: window['${promise}'].callbacks = window['${promise}'].callbacks || {}; window['${promise}'].callbacks.notify = (key, message) => window['${promise}'].callbacks[key].forEach(callback => callback(message)); window['${promise}'].callbacks['${name}'] = window['${promise}'].callbacks['${name}'] || []")
}
}

private fun notifyNamedCallback(promise: String, name: String, message: String) {
context.webView.loadUrl("javascript: window['${promise}'].callbacks.notify(${context.btoa(name)}, ${context.btoa(message)})")
}

/**
* @return the id of a promise on the window
Expand Down
5 changes: 4 additions & 1 deletion src/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,15 @@
window.clearAllMediaSessionEventListeners = function () {
window.mediaSessionListeners = {}
}
window.awaitAsyncResult = function (id) {
window.awaitAsyncResult = function (id, callbacks = {}) {
return new Promise((resolve, reject) => {
const interval = setInterval(async () => {
if (id in window) {
clearInterval(interval)
try {
if ('callbacks' in window[id]) {
Object.assign(window[id].callbacks, callbacks)
}
const result = await window[id].promise
resolve(Android.getSyncMessage(id))
} catch (ex) {
Expand Down

0 comments on commit c92fd7d

Please sign in to comment.