패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.3.0

streams_channel

StreamsChannel은 EventChannel에서 영감을 받았습니다. Flutter와 플랫폼 측 사이에 이벤트 스트림을 생성할 수 있게 해줍니다.

30일 다운로드
169
좋아요
14
Pub 점수
40

패키지 설치

flutter pub add streams_channel

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

StreamsChannel은 EventChannel에서 영감을 받은 Dart 패키지로, Flutter와 플랫폼 측 사이의 양방향 스트리밍 이벤트를 가능하게 합니다. Flutter가 네이티브 플랫폼(예: Android 또는 iOS)으로부터 지속적인 데이터 스트림을 수신하고 반대로도 전송할 수 있도록 하여 실시간 통신을 지원합니다. 플랫폼별 코드와의 원활한 통합을 위해 설계되었으며, 복잡한 보일러플레이트 없이 비동기 이벤트 흐름을 쉽게 처리할 수 있습니다. 가볍고 스트림 기반 상호작용에 집중되어 있어, 실시간 업데이트, 센서 데이터 또는 백그라운드 알림과 같은 사용 사례에 적합합니다.

사용 사례

  • 실시간 데이터 동기화
  • 센서 데이터 스트리밍
  • 백그라운드 작업 알림
  • 라이브 이벤트 방송
  • 플랫폼에서 Flutter로의 통신

주요 기능

  • 양방향 스트림 지원
  • 이벤트 채널을 위한 간단한 API
  • 경량이며 최소한의 종속성
  • 네이티브 플랫폼 통합
  • 이벤트 기반 아키텍처

적합한 대상

  • 실시간 기능을 구축하는 개발자
  • 플랫폼 측 이벤트 처리가 필요한 앱
  • 네이티브 플러그인을 사용하는 프로젝트
  • 비동기 데이터 흐름을 처리하는 팀
  • 네이티브 통합을 갖춘 플러터 앱

고려 사항

  • 플랫폼 측 구현이 필요합니다
  • 스트림 기반 통신에 제한됨
  • 내장된 오류 처리 없음
  • 단일 값 응답에 적합하지 않습니다
  • 양측의 올바른 설정에 의존합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

StreamsChannel for Flutter plugin development

pub package

StreamsChannel is inspired from EventChannel. It allows to create streams of events between Flutter and platform side.

Rationale

EventChannel allows to only create a single open stream per channel. On the first subscription, the stream will be open and it's possible to pass arguments from Flutter to platform side. Subsequent subscriptions will either re-use the open stream or override it with a new one.

In order to have multiple streams open at the same time, with different parameters for stream initialization, one has to create multiple EventChannel. And it gets complicated if the number of streams is dynamic.

Installation

Follow the instructions: https://pub.dev/packages/streams_channel#-installing-tab-

How it works

StreamsChannel works in a similar way than EventChannel. The difference is that it supports multiple open streams at the same time.

On the platform side, the channel takes a stream handler factory:

let channel = FlutterStreamsChannel(name: "my_channel", binaryMessenger: plugin.registrar.messenger())
channel.setStreamHandlerFactory { arguments in
  return MyHandler(arguments) // MyHandler is an instance FlutterStreamHandler
}

On the flutter side, each call to receiveBroadcastStream(args) will create a new stream, that won't replace any previous one that is still running.

  1. The first subscription to the stream will create a new stream handler using the factory on the platform side, then trigger onListen on the handler;
  2. The last subscription to the stream will trigger onCancel on the handler, then destroy the handler instance
  3. If a new first subscription happens afterwards, repeat step 1.

Under the hood, StreamsChannel tracks each stream with a simple auto-incremented unique id.

Example

Flutter side
final StreamsChannel channel = new StreamsChannel('some_channel');

// continuous stream of events from platform side, match some args
channel.receiveBroadcastStream('some args')
  .listen((data) {
    // do something
  });

// another continuous stream of events from platform side, matching some other args
channel.receiveBroadcastStream('some other args')
  .listen((data) {
    // do something
  });
Platform side
Android
public class DemoPlugin {
  public static void registerWith(PluginRegistry.Registrar registrar) {
    final StreamsChannel channel = new StreamsChannel(registrar.messenger(), "streams_channel_test");
    channel.setStreamHandlerFactory(new StreamsChannel.StreamHandlerFactory() {
      @Override
      public EventChannel.StreamHandler create(Object arguments) {
        return new StreamHandler();
      }
    });
  }

  // Send "Hello" 10 times, every second, then ends the stream
  public static class StreamHandler implements EventChannel.StreamHandler {

    private final Handler handler = new Handler();
    private final Runnable runnable = new Runnable() {
      @Override
      public void run() {
        if (count > 10) {
            eventSink.endOfStream();
        } else {
            eventSink.success("Hello " + count + "/10");
        }
        count++;
        handler.postDelayed(this, 1000);
      }
    };

    private EventChannel.EventSink eventSink;
    private int count = 1;

    @Override
    public void onListen(Object o, final EventChannel.EventSink eventSink) {
      this.eventSink = eventSink;
      runnable.run();
    }

    @Override
    public void onCancel(Object o) {
      handler.removeCallbacks(runnable);
    }
  }
}
iOS
@interface StreamHandler : NSObject<FlutterStreamHandler>
  @property(strong, nonatomic) NSTimer *timer;
  @property(assign, nonatomic) NSInteger count;
@end

@implementation DemoPlugin

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {

  FlutterStreamsChannel *channel = [FlutterStreamsChannel streamsChannelWithName:@"streams_channel_test" binaryMessenger:registrar.messenger];
  [channel setStreamHandlerFactory:^NSObject<FlutterStreamHandler> *(id arguments) {
    return [StreamHandler new];
  }];
}

@end

// Send "Hello" 10 times, every second, then ends the stream
@implementation StreamHandler

- (FlutterError *)onListenWithArguments:(id)arguments eventSink:(FlutterEventSink)events {
  self.count = 1;
  self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
    if(self.count > 10) {
      events(FlutterEndOfEventStream);
    } else {
      events([NSString stringWithFormat:@"Hello %ld/10", (long)self.count]);
      self.count++;
    }
  }];

  return nil;
}

- (FlutterError *)onCancelWithArguments:(id)arguments {
  [self.timer invalidate];
  self.timer = nil;
  return nil;
}
@end

Author

Beacons plugin is developed by Loup, a mobile development studio based in Montreal and Paris.
You can contact us at <hello@loup.app>

License

Apache License 2.0

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트