Skip to content

Commit

Permalink
fix: avoid auto unsubscribe (due to gc) in js env
Browse files Browse the repository at this point in the history
  • Loading branch information
zxch3n committed Oct 16, 2024
1 parent 00775d3 commit 3110ac1
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/loro-wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ rle = { path = "../rle", package = "loro-rle" }
tracing-wasm = "0.2.1"
tracing = { version = "0.1", features = ["release_max_level_warn"] }
serde_json = "1"
once_cell.workspace = true

[features]
default = []
20 changes: 17 additions & 3 deletions crates/loro-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use loro_internal::{
};
use rle::HasLength;
use serde::{Deserialize, Serialize};
use std::{cell::RefCell, cmp::Ordering, rc::Rc, sync::Arc};
use std::{cell::RefCell, cmp::Ordering, mem::ManuallyDrop, rc::Rc, sync::Arc};
use wasm_bindgen::{__rt::IntoJsResult, prelude::*, throw_val};
use wasm_bindgen_derive::TryFromJsValue;

Expand Down Expand Up @@ -4240,9 +4240,23 @@ fn js_to_export_mode(js_mode: JsExportMode) -> JsResult<ExportMode<'static>> {
}

fn subscription_to_js_function_callback(sub: Subscription) -> JsValue {
let mut sub = Some(sub);
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::Mutex;

static SUBSCRIPTION_MAP: Lazy<Mutex<HashMap<usize, Subscription>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
static NEXT_ID: Lazy<Mutex<usize>> = Lazy::new(|| Mutex::new(0));

let id = {
let mut id = NEXT_ID.lock().unwrap();
*id += 1;
*id
};

SUBSCRIPTION_MAP.lock().unwrap().insert(id, sub);
let closure = Closure::wrap(Box::new(move || {
if let Some(sub) = sub.take() {
if let Some(sub) = SUBSCRIPTION_MAP.lock().unwrap().remove(&id) {
sub.unsubscribe();
}
}) as Box<dyn FnMut()>);
Expand Down

0 comments on commit 3110ac1

Please sign in to comment.