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

[Bug] StreamSink lose infomation sometimes #1031

Closed
guchengxi1994 opened this issue Feb 8, 2023 · 8 comments
Closed

[Bug] StreamSink lose infomation sometimes #1031

guchengxi1994 opened this issue Feb 8, 2023 · 8 comments
Labels
bug Something isn't working

Comments

@guchengxi1994
Copy link

Describe the bug

I am using StreamSink to send information to flutter, but sometimes information would lose, only the last one will be accepted by flutter.
Here are codes.

  • flutter
import 'package:flutter/material.dart';

import 'bridge/native.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool started = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
                onPressed: () {
                  setState(() {
                    started = true;
                  });
                  api.startScan();
                },
                child: const Text("Start scan")),
            if (started)
              StreamBuilder(
                  stream: api.fileScanStream(),
                  builder: (c, d) {
                    print(d.data);
                    return Text(d.data.toString());
                  })
          ],
        ),
      ),
    );
  }
}
  • rust
use anyhow::Result;
use core::time;
use flutter_rust_bridge::StreamSink;
use std::{sync::RwLock, thread};

pub static SEND_TO_DART_FILE_STREAM_SINK: RwLock<Option<StreamSink<String>>> = RwLock::new(None);

pub fn file_scan_stream(s: StreamSink<String>) -> Result<()> {
    let mut stream = SEND_TO_DART_FILE_STREAM_SINK.write().unwrap();
    *stream = Some(s);
    Ok(())
}

pub fn start_scan() {
    thread::sleep(time::Duration::from_millis(10));

    let mut i = 0;

    loop {
        i += 1;
        if i >= 20 {
            break;
        } else {
            match SEND_TO_DART_FILE_STREAM_SINK.try_read() {
                Ok(s) => {
                    match s.as_ref() {
                        Some(s0) => {
                            let _f = String::from(format!("Test name {:?}",i) );
                            s0.add(_f);
                            // println!("got types: {:?}", l);
                        }
                        None => {
                            println!("Stream is None");
                        }
                    }
                }
                Err(_) => {
                    println!("Stream read error");
                }
            }
        }
    }
}

208_1

but if i add a sleep function to rust side, the stream works well
image

208_2

I dont know why this happened, and also, if i use tokio multi thread, to send infomation, even with a sleep function, some infomation still will lose.

Codegen logs with RUST_LOG=debug environment variable

PS D:\secret_data\filescan_client\small_demo> flutter_rust_bridge_codegen --rust-input native/src/api.rs --dart-output ./lib/bridge/bridge_generated.dart         2023/02/08 09:48:56 [WARN] Skipping unresolvable module web (tried \\?\D:\secret_data\filescan_client\small_demo\native\src\web.rs, \\?\D:\secret_data\filescan_client\small_demo\native\src\web\mod.rs, \\?\D:\secret_data\filescan_client\small_demo\native\src\bridge_generated\web.rs, \\?\D:\secret_data\filescan_client\small_demo\native\src\bridge_generated\web\mod.rs, )
2023/02/08 09:48:56 [WARN] Skipping unresolvable module io (tried \\?\D:\secret_data\filescan_client\small_demo\native\src\io.rs, \\?\D:\secret_data\filescan_client\small_demo\native\src\io\mod.rs, \\?\D:\secret_data\filescan_client\small_demo\native\src\bridge_generated\io.rs, \\?\D:\secret_data\filescan_client\small_demo\native\src\bridge_generated\io\mod.rs, )
Flutter 3.7.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 7048ed95a5 (6 days ago) • 2023-02-01 09:07:31 -0800
Engine • revision 800594f1f4
Tools • Dart 2.19.1 • DevTools 2.20.1
2023/02/08 09:48:57 [INFO] Picked config: Opts { rust_input_path: "D:\\secret_data\\filescan_client\\small_demo\\native/src/api.rs", dart_output_path: "D:\\secret_data\\filescan_client\\small_demo\\./lib/bridge/bridge_generated.dart", dart_decl_output_path: None, c_output_path: ["C:\\Users\\XIAOSH~1\\AppData\\Local\\Temp\\.tmpeqIQL6.h"], rust_crate_dir: "D:\\secret_data\\filescan_client\\small_demo\\native", rust_output_path: "D:\\secret_data\\filescan_client\\small_demo\\native/src\\bridge_generated.rs", class_name: "Native", dart_format_line_length: 80, skip_add_mod_to_lib: false, llvm_path: ["/opt/homebrew/opt/llvm", "/usr/local/opt/llvm", "/usr/lib/llvm-9", "/usr/lib/llvm-10", "/usr/lib/llvm-11", "/usr/lib/llvm-12", "/usr/lib/llvm-13", "/usr/lib/llvm-14", "/usr/lib/", "/usr/lib64/", "C:/Program Files/llvm", "C:/msys64/mingw64"], llvm_compiler_opts: "", manifest_path: "D:\\secret_data\\filescan_client\\small_demo\\native\\Cargo.toml", dart_root: Some("D:\\secret_data\\filescan_client\\small_demo"), build_runner: true, block_index: BlockIndex(0), skip_deps_check: false, wasm_enabled: false, inline_rust: false }    
2023/02/08 09:48:57 [INFO] Phase: Parse source code to AST, then to IR
Running in Directory: 'D:\secret_data\filescan_client\small_demo'Input Headers: [C:\Users\XIAOSH~1\AppData\Local\Temp\.tmp7BpVx8.h][WARNING]: Generated declaration '_Dart_Handle' start's with '_' and therefore will be private.
Finished, Bindings generated in C:\Users\XIAOSH~1\AppData\Local\Temp\.tmp5sK7zlthe path is "C:\\Users\\XIAOSH~1\\AppData\\Local\\Temp\\.tmpeqIQL6.h"2023/02/08 09:49:00 [INFO] Phase: Running build_runner
2023/02/08 09:49:00 [INFO] Phase: Formatting Dart code
Formatted D:\\secret_data\\filescan_client\\small_demo\\./lib/bridge/bridge_generated.dart
Formatted 1 file (1 changed) in 0.20 seconds.
2023/02/08 09:49:01 [INFO] Success!
2023/02/08 09:49:01 [INFO] Now go and use it :)

To Reproduce

No response

Expected behavior

No response

Generated binding code

No response

OS

windows 11

Version of flutter_rust_bridge_codegen

1.62.1

Flutter info

[✓] Flutter (Channel stable, 3.7.1, on Microsoft Windows [版本 10.0.22621.1105], locale zh-CN)
    • Flutter version 3.7.1 on channel stable at D:\flutter\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 7048ed95a5 (6 days ago), 2023-02-01 09:07:31 -0800
    • Engine revision 800594f1f4
    • Dart version 2.19.1
    • DevTools version 2.20.1
    • Pub download mirror https://pub.flutter-io.cn
    • Flutter download mirror https://storage.flutter-io.cn

[✗] Windows Version (Unable to confirm if installed Windows version is 10 or greater)

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at D:\androidSDK
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.

[✓] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[✓] Visual Studio - develop for Windows (Visual Studio Community 2022 17.3.1)
    • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community
    • Visual Studio Community 2022 version 17.3.32811.315
    • Windows 10 SDK version 10.0.19041.0

[✓] Android Studio (version 4.1)
    • Android Studio at D:\AndroidStudio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[✓] IntelliJ IDEA Ultimate Edition (version 2020.2)
    • IntelliJ at D:\IntelliJ IDEA 2020.2.3
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] Connected device (3 available)
    • Windows (desktop) • windows • windows-x64    • Microsoft Windows [版本 10.0.22621.1105]
    • Chrome (web)      • chrome  • web-javascript • Google Chrome 109.0.5414.120
    • Edge (web)        • edge    • web-javascript • Microsoft Edge 109.0.1518.78

[✓] HTTP Host Availability
    • All required HTTP hosts are available

Version of clang++

No response

Version of ffigen

6.1.2

Additional context

No response

@guchengxi1994 guchengxi1994 added the bug Something isn't working label Feb 8, 2023
@welcome
Copy link

welcome bot commented Feb 8, 2023

Hi! Thanks for opening your first issue here! 😄

@fzyzcjy
Copy link
Owner

fzyzcjy commented Feb 8, 2023

Hmm looks like the stream has not been there, i.e. StreamSink is None?

@guchengxi1994
Copy link
Author

StreamSink is None at the first time, but when I clicked more times, it is not None. You can see the former gif, after I clicked the button several times, the stream returns Test name 19, but Test name 0 to Test name 18 are missing.

@fzyzcjy
Copy link
Owner

fzyzcjy commented Feb 8, 2023

Without detailed examination, I guess then you are just sending data to the old stream while you indeed want to see data in the new stream.

@guchengxi1994
Copy link
Author

Is this problem related to #517? I found that issue the stream is None too.

@rogurotus
Copy link
Contributor

looks familiar, but I'm not sure.
You can try stream.listen(_).onData(function)

@guchengxi1994
Copy link
Author

@fzyzcjy @rogurotus using a stream.listen(e){ setState() }, not using stream in StreamBuilder solves the problem, thanks!

@github-actions
Copy link
Contributor

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 23, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants