Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

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

22 changes: 16 additions & 6 deletions livekit-protocol/src/promise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use tokio::sync::{oneshot, Mutex};
use tokio::sync::{oneshot, Mutex, RwLock};

pub struct Promise<T> {
tx: Mutex<Option<oneshot::Sender<T>>>,
rx: Mutex<Option<oneshot::Receiver<T>>>,
result: Mutex<Option<T>>,
result: RwLock<Option<T>>,
}

impl<T: Clone> Promise<T> {
Expand All @@ -37,14 +37,24 @@ impl<T: Clone> Promise<T> {
}

pub async fn result(&self) -> T {
{
let result_read = self.result.read().await;
if let Some(result) = result_read.clone() {
return result;
}
}

let mut rx = self.rx.lock().await;
if rx.is_some() {
self.result.lock().await.replace(rx.take().unwrap().await.unwrap());
if let Some(rx) = rx.take() {
let result = rx.await.unwrap();
*self.result.write().await = Some(result.clone());
result
} else {
self.result.read().await.clone().unwrap()
}
self.result.lock().await.clone().unwrap()
}

pub fn try_result(&self) -> Option<T> {
self.result.try_lock().unwrap().clone()
self.result.try_read().unwrap().clone()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't try_read also panicking? when unwrapping?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, good catch! Thank you. I believe a panic would occur if a write lock is held.

So in this case, I'll modify it to return None instead of unwrapping. Since Promise is designed to acquire the write lock only once, this should not be an issue.

}
}
Loading