Flutter核心编排插件zef_orchestration_core的使用

Flutter核心编排插件zef_orchestration_core的使用

本Dart库提供了一种灵活且高效的方式来处理和编排请求,采用命令查询模式。它旨在促进命令和查询操作的分离,从而为复杂应用构建清晰且可维护的代码结构。

特性

  • 通用请求处理:定义处理特定类型请求的处理器,并返回相应的结果。
  • 命令与查询分离:将命令和查询操作的处理分开,以明确区分更改状态的操作和检索数据的操作。
  • 异步支持:内置对异步操作的支持,使非阻塞I/O操作成为可能。
  • 单例编排器:中央编排器实例用于管理命令和查询处理器,确保单一编排点。

开始使用

安装

要在您的Dart或Flutter项目中集成此库,请在pubspec.yaml文件中添加以下依赖项:

dependencies:
  zef_orchestration_core: latest_version

快速入门

初始化编排器

在使用Orchestrator之前,需要先初始化它:

void main() {
  OrchestratorBuilder().build();
}

如果您已经实现了一个自定义的OrchestratorAdapter,则应该使用它来初始化Orchestrator

void main() {
  OrchestratorBuilder()
    .withAdapter(YourCustomOrchestratorAdapter())
    .build();
}

定义请求和处理器

创建您的命令和查询请求及其对应的处理器。每个处理器都应该实现相应的抽象处理器类:

class SampleCommand extends Command {
  // 实现细节
}

class SampleCommandHandler extends CommandHandler<SampleCommand> {
  [@override](/user/override)
  Future<void> call(SampleCommand command) async {
    // 命令处理逻辑
  }
}

向编排器注册处理器

向编排器注册您的命令和查询处理器,以便启用它们的处理:

Orchestrator.I.registerCommandHandler(SampleCommandHandler());

使用编排器发送命令和查询

通过编排器发送命令和查询,并根据需要处理结果:

await Orchestrator.I.publish(SampleCommand());
// 对于带有预期结果的查询
var queryResult = await Orchestrator.I.send(SampleQuery());

使用工厂注册处理器

您还可以通过工厂注册您的RequestHandler,这样实例就不会存储在内存中。这可以减少内存使用,但请注意,当发送或发布请求时,这可能会导致性能下降,因为Orchestrator试图解析一个实例。然而,如果您通过依赖注入将RequestHandler作为Lazy注册,则RequestHandler实例将在第一次需要时解析。这减少了启动时间和内存使用量。因此,我们建议采取这种方式。

Orchestrator.I.registerCommandHandlerFactory(() => SampleCommandHandler());

注意:这是一个工厂,每次发送适当的Command时都会直接返回一个实例。

贡献

欢迎为本库做出贡献。请随时提交拉取请求或打开问题讨论拟议的更改或增强功能。


示例代码

以下是一个完整的示例代码,展示了如何使用zef_orchestration_core插件:

import 'package:zef_orchestration_core/zef_orchestration_core.dart';

class SampleCommand extends Command {}

class SampleCommandHandler extends CommandHandler<SampleCommand> {
  [@override](/user/override)
  Future<void> call(SampleCommand command) async {
    print('Executing SampleCommand...');
    // 命令执行逻辑
  }
}

// 定义一个样本查询及其处理器。
class SampleQuery extends Query<String> {}

class SampleQueryHandler extends QueryHandler<SampleQuery, String> {
  [@override](/user/override)
  Future<String> call(SampleQuery query) async {
    print('Executing SampleQuery...');
    return 'Query Result';
  }
}

void main() async {
  // 初始化编排器使用简单适配器。
  OrchestratorBuilder().build();

  // 注册命令和查询处理器。
  await Orchestrator.I.registerCommandHandler(SampleCommandHandler());
  await Orchestrator.I.registerQueryHandler(SampleQueryHandler());

  // 发布一个命令。
  await Orchestrator.I.publish(SampleCommand());

  // 发送查询并等待结果。
  final result = await Orchestrator.I.send(SampleQuery());
  print('Query returned: $result');

  // 可选地,注销所有处理器。
  await Orchestrator.I.unregisterAll();
}

更多关于Flutter核心编排插件zef_orchestration_core的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter核心编排插件zef_orchestration_core的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用zef_orchestration_core插件的示例代码。zef_orchestration_core是一个核心编排插件,它可以帮助你管理和协调复杂的异步操作。为了演示如何使用它,我们假设一个简单的场景:从两个不同的API获取数据并进行组合。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加zef_orchestration_core的依赖:

dependencies:
  flutter:
    sdk: flutter
  zef_orchestration_core: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来获取依赖。

2. 导入包

在你的Dart文件中导入zef_orchestration_core包:

import 'package:zef_orchestration_core/zef_orchestration_core.dart';

3. 定义API调用函数

假设你有两个API调用函数,一个获取用户信息,另一个获取用户帖子信息:

Future<Map<String, dynamic>> fetchUserInfo() async {
  // 模拟API调用,实际使用中应替换为真实的API请求
  await Future.delayed(Duration(seconds: 1));
  return {
    'userId': 1,
    'name': 'John Doe',
  };
}

Future<List<Map<String, dynamic>>> fetchUserPosts() async {
  // 模拟API调用,实际使用中应替换为真实的API请求
  await Future.delayed(Duration(seconds: 2));
  return [
    {'postId': 1, 'title': 'First Post'},
    {'postId': 2, 'title': 'Second Post'},
  ];
}

4. 使用Orchestrator进行编排

现在,你可以使用Orchestrator来编排这两个API调用:

void main() async {
  Orchestrator orchestrator = Orchestrator();

  // 添加任务
  orchestrator.addTask(
    name: 'fetchUserInfo',
    task: fetchUserInfo,
  );

  orchestrator.addTask(
    name: 'fetchUserPosts',
    task: fetchUserPosts,
    dependencies: ['fetchUserInfo'],  // 表示fetchUserPosts依赖于fetchUserInfo
  );

  // 监听任务完成
  orchestrator.listen(
    onTaskCompleted: (OrchestratorTask task) {
      print('Task ${task.name} completed with result: ${task.result}');
    },
    onOrchestratorCompleted: () {
      print('All tasks completed.');
      // 在这里,你可以安全地使用所有任务的结果
      orchestrator.tasks.forEach((task) {
        if (task.name == 'fetchUserInfo') {
          Map<String, dynamic> userInfo = task.result as Map<String, dynamic>;
          print('User Info: $userInfo');
        } else if (task.name == 'fetchUserPosts') {
          List<Map<String, dynamic>> userPosts =
              task.result as List<Map<String, dynamic>>;
          print('User Posts: $userPosts');
        }
      });
    },
    onError: (error, stackTrace) {
      print('Error occurred: $error');
    },
  );

  // 开始执行编排
  await orchestrator.run();
}

5. 在Flutter Widget中使用

如果你需要在Flutter的Widget中使用这个编排逻辑,你可以将上述代码放入一个异步函数中,并在initState中调用它。例如:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future<void> _fetchData() async {
    Orchestrator orchestrator = Orchestrator();

    orchestrator.addTask(
      name: 'fetchUserInfo',
      task: fetchUserInfo,
    );

    orchestrator.addTask(
      name: 'fetchUserPosts',
      task: fetchUserPosts,
      dependencies: ['fetchUserInfo'],
    );

    orchestrator.listen(
      onOrchestratorCompleted: () {
        setState(() {
          // 更新UI,使用orchestrator.tasks中的结果
        });
      },
      onError: (error, stackTrace) {
        // 处理错误
      },
    );

    await orchestrator.run();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Orchestration Demo'),
      ),
      body: Center(
        child: Text('Loading...'),  // 在数据加载完成前显示加载中
      ),
    );
  }
}

在这个例子中,UI更新部分(setState)和数据展示部分需要根据实际需求进行实现。上面的代码仅展示了如何使用zef_orchestration_core进行任务编排和依赖管理。

回到顶部