Observable.combineLatest2 is not streaming when page is loaded through navigation

I am creating a flutter app with blocs.

I followed the code available in Flutter login with blocs

It works as expected, if my app has no routes defined

class App extends StatelessWidget {
  Widget build(BuildContext context) {
    return Provider(
      child: MaterialApp(
        title: 'Log Me In!',
        home: Scaffold(
          body: LoginScreen(),
        ),
      ),
    ); 
  }
}

but when I change my app to use routes

class App extends StatelessWidget {
  Widget build(BuildContext context) {
    return  MaterialApp(
        title: 'Log Me In!',
        routes: {
          '/':(context) => Provider(
            child: Scaffold(
              body: LoginScreen(),
            ),
          )
        },
       );
  }
}

bloc code

class Bloc extends Object with Validators {
  final _email = BehaviorSubject<String>();
  final _password = BehaviorSubject<String>();

  // retrieve data from stream
  Stream<String> get email    => _email.stream.transform(validateEmail);
  Stream<String> get password => _password.stream.transform(validatePassword);
  Stream<bool>   get submitValid => Observable.combineLatest2(email, password, (e, p) => true);

  // add data to stream
  Function(String) get changeEmail    => _email.sink.add;
  Function(String) get changePassword => _password.sink.add;

  submit() {
    final validEmail    = _email.value;
    final validPassword = _password.value;

    print('$validEmail and $validPassword');
  }

  dispose() {
    _email.close();
    _password.close();
  }
}

Observable.combileLatest2 is not streaming the data (but it streams error though).

Using Rxdart version 0.19.0 and

Flutter 1.0.0 • channel beta •https://github.com/flutter/flutter.git Framework • revision 5391447fae (6 days ago) • 2018-11-29 19:41:26-0800 Engine • revision 7375a0f414Tools • Dart 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

Am I doing something wrong here? thanks in advance

1 possible answer(s) on “Observable.combineLatest2 is not streaming when page is loaded through navigation

  1. After lot of trial, I found that when I used routes for the navigation, flutter will build the page multiple times and thats the expected behavior refer here

    So when it builds the page multiple times, it was creating multiple Observables on the bloc as it was creating new instance of Bloc every time it creates the Page route.

    So when I modify the code

    class App extends StatelessWidget {
      final login = Provider(
                child: Scaffold(
                  body: LoginScreen(),
                ),
              );
      Widget build(BuildContext context) {
        return  MaterialApp(
            title: 'Log Me In!',
            routes: {
              '/':(context) => login,
            },
           );
      }
    }
    

    it worked perfectly.

    The other way is to achieve is to create a stateful widget and do the initialization in the init method.