Skip to content

Commit

Permalink
refactor: use async OnceCell
Browse files Browse the repository at this point in the history
  • Loading branch information
SeaDve committed Feb 8, 2024
1 parent 5bf4090 commit a20efbc
Showing 1 changed file with 19 additions and 30 deletions.
49 changes: 19 additions & 30 deletions src/album_art.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use std::{
cell::{OnceCell, RefCell},
collections::HashMap,
rc::Rc,
};
use std::{cell::RefCell, collections::HashMap, rc::Rc};

use anyhow::{Context, Result};
use futures_util::lock::Mutex;
use async_lock::OnceCell;
use gtk::{gdk, glib};
use soup::prelude::*;

Expand Down Expand Up @@ -44,9 +40,7 @@ impl AlbumArtStore {
pub struct AlbumArt {
session: soup::Session,
download_url: String,

cache: OnceCell<gdk::Texture>,
cache_guard: Mutex<()>,
}

impl AlbumArt {
Expand All @@ -55,41 +49,36 @@ impl AlbumArt {
session,
download_url: download_url.to_string(),
cache: OnceCell::new(),
cache_guard: Mutex::new(()),
}
}

/// Whether the album art is loaded in memory.
pub fn is_loaded(&self) -> bool {
self.cache.get().is_some()
self.cache.is_initialized()
}

pub fn download_url(&self) -> &str {
&self.download_url
}

pub async fn texture(&self) -> Result<&gdk::Texture> {
let _guard = self.cache_guard.lock().await;

if let Some(texture) = self.cache.get() {
return Ok(texture);
}

let bytes = self
.session
.send_and_read_future(
&soup::Message::new("GET", &self.download_url)?,
glib::Priority::LOW,
)
self.cache
.get_or_try_init(|| async {
let bytes = self
.session
.send_and_read_future(
&soup::Message::new("GET", &self.download_url)?,
glib::Priority::LOW,
)
.await
.context("Failed to download album art bytes")?;
tracing::trace!(download_url = ?self.download_url, "Downloaded album art bytes");

let texture = gdk::Texture::from_bytes(&bytes)
.context("Failed to load album art texture from bytes")?;
Ok(texture)
})
.await
.context("Failed to download album art bytes")?;
tracing::trace!(download_url = ?self.download_url, "Downloaded album art bytes");

let texture = gdk::Texture::from_bytes(&bytes)
.context("Failed to load album art texture from bytes")?;
self.cache.set(texture).unwrap();

Ok(self.cache.get().unwrap())
}
}

Expand Down

0 comments on commit a20efbc

Please sign in to comment.