【发布时间】:2019-07-31 13:34:01
【问题描述】:
我正在开发一个小型颤振应用程序,我在其中使用本机库进行一些计算。 dart 和 java(在 android 上)之间的通信是双向的,为此使用 methodChannels。 我从 dart 调用 await in_channel.invokeMethod("someJavaMethod") 来开始计算。这会从 Java 触发本机库的初始化。此初始化的结果作为异步 JNI 调用返回,然后触发 out_channel.invokeMethod("someDartMethod")。
我的计划是将 out_channel 绑定到本地 dart 广播流,这样我就可以调用 someJavaMethod 然后等待 myMethodStream.where((m) => m.method == "someDartMethod")...
问题是“someDartMethod”可以在“someJavaMethod”调用返回之前出现。
我所拥有的组合代码示例:
static const MethodChannel _channel_in = const
MethodChannel('native_lib_wrapper_out');
static const MethodChannel _channel_out = const
MethodChannel('native_lib_wrapper_in');
final StreamController<MethodCall> _methodStreamController = new
StreamController.broadcast();
NativeLibWrapper._() {
_channel_in.setMethodCallHandler((MethodCall call) {
_methodStreamController.add(call);
return;
});
}
Future<Map<dynamic,dynamic>> initLib(String id, String filePath)
async {
Map<dynamic,dynamic> ret;
ret = await _channel_out.invokeMethod("initLib", <String,
dynamic> { // data to be passed to the function
'id': id,
'filePath': filePath,
});
print('initLib - invokeMethod done. wait for stream');
if(ret["status"] == 0) {
await NativeLibWrapper.instance._methodStream
.where((m) => m.method == "libInitEnded")
.map((m){
var args = m.arguments;
ret = args;
}).first;
}
return ret;
}
我本来希望代码在我的流上获取方法调用 libInitEnded,然后它应该在该点之后返回,但它不断挂在流上的等待中,从日志看来,在打印之前调用了 libInitEnded在中间。
那么有没有更好的方法来构建它?它不会是唯一来回的方法,所以我希望能得到一个好的稳定的解决方案。
【问题讨论】: