ReactiveX / rxdart

The Reactive Extensions for Dart
http://reactivex.io
Apache License 2.0
3.37k stars 271 forks source link

map method executes every time BehaviorSubject adds event #618

Closed hahai96 closed 3 years ago

hahai96 commented 3 years ago

Hi, I'm using BehaviorSubject, when i use map method and add data to subject, method map is executed each time data is added by subject. Is this an error?

rxdart: ^0.27.1 flutter: 2.2.1

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  BehaviorSubject replaySubject = BehaviorSubject();

  StreamSubscription? subscription;

  int count = 0;

  void mapData() {
    subscription?.cancel();

    subscription = replaySubject.map((event) => event).listen((event) {
      print("===> event $event");
    });
  }

  void addData() {
    replaySubject.add(count++);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              onPressed: mapData,
              child: Text('ok'),
            ),
            FlatButton(
              onPressed: addData,
              child: Text('ok2'),
            )
          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}