Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use new LazyLock to store message channels #423

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 2 additions & 4 deletions documentation/docs/frequently-asked-questions.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,10 @@ onPressed: () async {
```

```rust title="native/hub/src/sample_functions.rs"
pub async fn respond() -> Result<()> {
pub async fn respond() {
use messages::tutorial_resource::*;

let receiver = MyUniqueInput::get_dart_signal_receiver()?;
let receiver = MyUniqueInput::get_dart_signal_receiver();
while let Some(dart_signal) = receiver.recv().await {
let my_unique_input = dart_signal.message;
MyUniqueOutput {
Expand All @@ -245,8 +245,6 @@ pub async fn respond() -> Result<()> {
}
.send_signal_to_dart();
}

Ok(())
}
```

Expand Down
4 changes: 2 additions & 2 deletions documentation/docs/messaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ MyDataInput( ... ).sendSignalToRust();
```

```rust title="Rust"
let receiver = MyDataInput::get_dart_signal_receiver()?;
let receiver = MyDataInput::get_dart_signal_receiver();
while let Some(dart_signal) = receiver.recv().await {
let message: MyDataInput = dart_signal.message;
// Custom Rust logic here
Expand All @@ -88,7 +88,7 @@ MyDataInput( ... ).sendSignalToRust(binary);
```

```rust title="Rust"
let receiver = MyDataInput::get_dart_signal_receiver()?;
let receiver = MyDataInput::get_dart_signal_receiver();
while let Some(dart_signal) = receiver.recv().await {
let message: MyDataInput = dart_signal.message;
let binary: Vec<u8> = dart_signal.binary;
Expand Down
12 changes: 4 additions & 8 deletions documentation/docs/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ use crate::common::*;
use crate::messages;
use rinf::debug_print;

pub async fn calculate_precious_data() -> Result<()> {
pub async fn calculate_precious_data() {
use messages::tutorial_messages::*;

let receiver = MyPreciousData::get_dart_signal_receiver()?; // GENERATED
let receiver = MyPreciousData::get_dart_signal_receiver(); // GENERATED
while let Some(dart_signal) = receiver.recv().await {
let my_precious_data = dart_signal.message;

Expand All @@ -79,8 +79,6 @@ pub async fn calculate_precious_data() -> Result<()> {
debug_print!("{new_numbers:?}");
debug_print!("{new_string}");
}

Ok(())
}
```

Expand Down Expand Up @@ -217,18 +215,16 @@ children: [
use crate::common::*;
use crate::messages;

pub async fn tell_treasure() -> Result<()> {
pub async fn tell_treasure() {
use messages::tutorial_messages::*;

let mut current_value: i32 = 1;

let receiver = MyTreasureInput::get_dart_signal_receiver()?; // GENERATED
let receiver = MyTreasureInput::get_dart_signal_receiver(); // GENERATED
while let Some(_) = receiver.recv().await {
MyTreasureOutput { current_value }.send_signal_to_dart(); // GENERATED
current_value += 1;
}

Ok(())
}
```

Expand Down
59 changes: 8 additions & 51 deletions flutter_package/bin/src/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ use rinf::{
DartSignal, MessageReceiver, MessageSender,
RinfError,
};
use std::sync::Mutex;
use std::sync::LazyLock;

''',
atFront: true,
Expand All @@ -289,38 +289,16 @@ use std::sync::Mutex;
await insertTextToFile(
rustPath,
'''
type ${messageName}Cell = Mutex<Option<(
type ${messageName}Cell = LazyLock<(
MessageSender<DartSignal<${normalizePascal(messageName)}>>,
Option<MessageReceiver<DartSignal<${normalizePascal(messageName)}>>>,
)>>;
MessageReceiver<DartSignal<${normalizePascal(messageName)}>>,
)>;
pub static ${snakeName.toUpperCase()}_CHANNEL: ${messageName}Cell =
Mutex::new(None);
LazyLock::new(message_channel);

impl ${normalizePascal(messageName)} {
pub fn get_dart_signal_receiver()
-> Result<MessageReceiver<DartSignal<Self>>, RinfError>
{
let mut guard = ${snakeName.toUpperCase()}_CHANNEL
.lock()
.map_err(|_| RinfError::LockMessageChannel)?;
if guard.is_none() {
let (sender, receiver) = message_channel();
guard.replace((sender, Some(receiver)));
}
let (mut sender, mut receiver_option) = guard
.take()
.ok_or(RinfError::NoMessageChannel)?;
// After Dart's hot restart or app reopen on mobile devices,
// a sender from the previous run already exists
// which is now closed.
if sender.is_closed() {
let receiver;
(sender, receiver) = message_channel();
receiver_option = Some(receiver);
}
let receiver = receiver_option.ok_or(RinfError::MessageReceiverTaken)?;
guard.replace((sender, None));
Ok(receiver)
pub fn get_dart_signal_receiver() -> MessageReceiver<DartSignal<Self>> {
${snakeName.toUpperCase()}_CHANNEL.1.clone()
}
}
''',
Expand Down Expand Up @@ -467,28 +445,7 @@ new_hash_map.insert(
message,
binary: binary.to_vec(),
};
let mut guard = ${snakeName.toUpperCase()}_CHANNEL
.lock()
.map_err(|_| RinfError::LockMessageChannel)?;
if guard.is_none() {
let (sender, receiver) = message_channel();
guard.replace((sender, Some(receiver)));
}
let mut pair = guard
.as_ref()
.ok_or(RinfError::NoMessageChannel)?;
// After Dart's hot restart or app reopen on mobile devices,
// a sender from the previous run already exists
// which is now closed.
if pair.0.is_closed() {
let (sender, receiver) = message_channel();
guard.replace((sender, Some(receiver)));
pair = guard
.as_ref()
.ok_or(RinfError::NoMessageChannel)?;
}
let sender = &pair.0;
let _ = sender.send(dart_signal);
${snakeName.toUpperCase()}_CHANNEL.0.send(dart_signal);
Ok(())
}),
);
Expand Down
11 changes: 4 additions & 7 deletions flutter_package/example/native/hub/src/sample_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ static IS_DEBUG_MODE: bool = true;
static IS_DEBUG_MODE: bool = false;

// Business logic for the counter widget.
pub async fn tell_numbers() -> Result<()> {
pub async fn tell_numbers() {
use messages::counter_number::*;

let mut vector = Vec::new();

// Stream getter is generated from a marked Protobuf message.
let receiver = SampleNumberInput::get_dart_signal_receiver()?;
let receiver = SampleNumberInput::get_dart_signal_receiver();
while let Some(dart_signal) = receiver.recv().await {
// Extract values from the message received from Dart.
// This message is a type that's declared in its Protobuf file.
Expand All @@ -40,8 +40,6 @@ pub async fn tell_numbers() -> Result<()> {
}
.send_signal_to_dart();
}

Ok(())
}

// Business logic for the fractal image.
Expand Down Expand Up @@ -104,15 +102,14 @@ pub async fn stream_fractal() {

// A dummy function that uses sample messages to eliminate warnings.
#[allow(dead_code)]
async fn use_messages() -> Result<()> {
async fn use_messages() {
use messages::sample_folder::sample_file::*;
let _ = SampleInput::get_dart_signal_receiver()?;
let _ = SampleInput::get_dart_signal_receiver();
SampleOutput {
kind: 3,
oneof_input: Some(sample_output::OneofInput::Age(25)),
}
.send_signal_to_dart();
Ok(())
}

// Business logic for testing various crates.
Expand Down
6 changes: 2 additions & 4 deletions flutter_package/template/native/hub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,16 @@ async fn main() -> Result<()> {
Ok(())
}

async fn communicate() -> Result<()> {
async fn communicate() {
use messages::basic::*;

// Send signals to Dart like below.
SmallNumber { number: 7 }.send_signal_to_dart();

// Get receivers that listen to Dart signals like below.
let receiver = SmallText::get_dart_signal_receiver()?;
let receiver = SmallText::get_dart_signal_receiver();
while let Some(dart_signal) = receiver.recv().await {
let message: SmallText = dart_signal.message;
rinf::debug_print!("{message:?}");
}

Ok(())
}
Loading