fzyzcjy / flutter_rust_bridge

Flutter/Dart <-> Rust binding generator, feature-rich, but seamless and simple.
https://fzyzcjy.github.io/flutter_rust_bridge/
MIT License
4.09k stars 278 forks source link

Support for exposing `SendPort` like `StreamSink`? #586

Closed LLouice closed 1 year ago

LLouice commented 2 years ago

Is your feature request related to a problem? Please describe.

Currently,we need wrap async function in a sync function,and generally the async task run in a seperate async runtime(or block on current thread), if the async task has return value, it will block the thread(one thread of thread pool) to wait the result.

If we have many long running tasks, it'll run out of all threads of the thread pool.

How about cancel this waiting, just let task itself return it's result in async runtime.

Describe the solution you'd like

I found a article: Dart and Rust: the async story of shekohex, he shows a solution: async runtime captures the Isolate and when task is Ready, post the result through isolate handle directly.

The relevant code is as follows:

https://github.com/shekohex/flutterust/blob/9ab881627a42294114e54e039dc293df14df4e7e/native/scrap-ffi/src/lib.rs#L71

#[no_mangle]
pub extern "C" fn load_page(port: i64, url: *const raw::c_char) -> i32 {
    let rt = runtime!();
    let url = cstr!(url);
    rt.spawn(async move {
        let result = scrap::load_page(url).await;
        let isolate = Isolate::new(port);
        isolate.post(result); // <---
    });
    1
}
fzyzcjy commented 2 years ago

Btw about async in Rust, here are some previous doc: http://cjycode.com/flutter_rust_bridge/feature/async_rust.html, http://cjycode.com/flutter_rust_bridge/article/async_in_rust.html, by @AlienKevin

fzyzcjy commented 2 years ago

This lib is trying to provide safe and automatic wrappers. Therefore, it may be a bit too low-level if we directly expose SendPort.

However, there seems to be a solution: What about improving the code generator, such that it automatically generate code similar to what you have mentioned.

Feel free to PR and I am looking forward to review it :)

/cc @Desdaemon btw what do you think?

Desdaemon commented 2 years ago

This is related to the ongoing work for web support, but SendPort is only an implementation detail! (MessagePort replaces it on the web.) Regardless, their API is roughly similar so we can try to abstract over their differences, but I'll have to work more on the web support to have a definite answer.

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

github-actions[bot] commented 1 year ago

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.