1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use std::marker::PhantomData;

pub use allo_isolate::ffi::DartCObject;
pub use allo_isolate::IntoDart;
use allo_isolate::Isolate;

#[derive(Copy, Clone)]
pub struct Rust2Dart {
    isolate: Isolate,
}

const RUST2DART_ACTION_SUCCESS: i32 = 0;
const RUST2DART_ACTION_ERROR: i32 = 1;
const RUST2DART_ACTION_CLOSE_STREAM: i32 = 2;

// api signatures is similar to Flutter Android's callback https://api.flutter.dev/javadoc/io/flutter/plugin/common/MethodChannel.Result.html
impl Rust2Dart {
    pub fn new(port: i64) -> Self {
        Rust2Dart {
            isolate: Isolate::new(port),
        }
    }

    pub fn success<T: IntoDart>(&self, result: T) -> bool {
        self.isolate.post(vec![
            RUST2DART_ACTION_SUCCESS.into_dart(),
            result.into_dart(),
        ])
    }

    pub fn error(&self, error_code: String, error_message: String) -> bool {
        self.error_full(error_code, error_message, ())
    }

    pub fn error_full(
        &self,
        error_code: String,
        error_message: String,
        error_details: impl IntoDart,
    ) -> bool {
        self.isolate.post(vec![
            RUST2DART_ACTION_ERROR.into_dart(),
            error_code.into_dart(),
            error_message.into_dart(),
            error_details.into_dart(),
        ])
    }

    pub fn close_stream(&self) -> bool {
        self.isolate
            .post(vec![RUST2DART_ACTION_CLOSE_STREAM.into_dart()])
    }
}

pub struct TaskCallback {
    rust2dart: Rust2Dart,
}

impl TaskCallback {
    pub fn new(rust2dart: Rust2Dart) -> Self {
        Self { rust2dart }
    }

    pub fn stream_sink<T: IntoDart>(&self) -> StreamSink<T> {
        StreamSink::new(self.rust2dart)
    }
}

#[derive(Clone)]
pub struct StreamSink<T: IntoDart> {
    rust2dart: Rust2Dart,
    _phantom_data: PhantomData<T>,
}

impl<T: IntoDart> StreamSink<T> {
    pub fn new(rust2dart: Rust2Dart) -> Self {
        Self {
            rust2dart,
            _phantom_data: PhantomData,
        }
    }

    pub fn add(&self, value: T) -> bool {
        self.rust2dart.success(value)
    }

    pub fn close(&self) -> bool {
        self.rust2dart.close_stream()
    }
}