Skip to content

Instantly share code, notes, and snippets.

@eriadam
Last active May 14, 2020 20:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eriadam/cc969929daabe2daa21183b2c2a911c7 to your computer and use it in GitHub Desktop.
Save eriadam/cc969929daabe2daa21183b2c2a911c7 to your computer and use it in GitHub Desktop.
iOS-JavaScript sharing data full example
/**
* Having imported:
*
* bluebird.min.js
* rx.js
*/
// Business Logic
async function doStuff() {
// Get query from user
let query = await someModalWillReturnThis();
// Load data from DB
let data = await fetchDataFromDatabase(query);
// Show results to user
UI.update(data);
}
function fetchDataFromDatabase(query) {
// Calling iOS method here
location.href = `app://loadStuff`
// Returning the Promise
return new Promise((resolve, reject) => {
// Timeout and reject.
let timeout = setTimeout(() => reject(new Error('Timeout')), 3000);
// Observing the call to the callback
Rx
.Observable
.create(function subscribe(observer) {
// This will be called by the iOS client
didReceiveDataFromDatabase = function(data) {
// Parse, process your data if needed.
observer.next(JSON.parse(data));
}
})
.subscribe(result => {
// Receiving data here, resolving promise
clearTimeout(timeout)
resolve(result);
});
});
}
// We declare this as the default action.
function didReceiveDataFromDatabase(data) {
console.log('didReceiveDataFromDatabase', data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment