Skip to content

Commit

Permalink
Avoid having to clone during drop
Browse files Browse the repository at this point in the history
Use `Option`s in `AddressSubscription`, because they can be `take`n.
  • Loading branch information
sisou authored and jsdanielh committed May 21, 2024
1 parent 9b40e58 commit ad7ec90
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions web-client/src/client/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,8 +532,10 @@ impl Client {
let consensus = self.inner.consensus_proxy();

struct AddressSubscription {
address: nimiq_keys::Address,
consensus: ConsensusProxy,
// Use Options to be able to take the address and consensus out of the
// struct during drop, avoiding another clone.
address: Option<nimiq_keys::Address>,
consensus: Option<ConsensusProxy>,
}
impl AddressSubscription {
pub async fn subscribe(
Expand All @@ -543,13 +545,16 @@ impl Client {
consensus
.subscribe_to_addresses(vec![address.clone()], 1, None)
.await?;
Ok(Self { address, consensus })
Ok(Self {
address: Some(address),
consensus: Some(consensus),
})
}
}
impl Drop for AddressSubscription {
fn drop(&mut self) {
let address = self.address.clone();
let consensus = self.consensus.clone();
let address = self.address.take().unwrap();
let consensus = self.consensus.take().unwrap();
// Unsubscribe from the address without caring about the result
spawn_local(async move {
let _ = consensus.unsubscribe_from_addresses(vec![address], 1).await;
Expand Down

0 comments on commit ad7ec90

Please sign in to comment.