Search code examples
dartdart-async

Make function to return custom stream


Is it possible to create a function that returns a custom stream and handles it like this?

user.logIn('owner', '1234')
.listen(
  success (Object user) {
    print(user);
  },
  error: (Object user, Object error) {
    print(error);
  }
);

Solution

  • Something like:

    class LoginResult {
      bool success = false;
      String username;
    }
    
    Stream<LoginResult> onLogin() async* {
      while(...) {
        yield new LoginResult()
          ..success = isSuccess
          ..userName = 'someUser';
      }
    }
    

    or

    StreamController<LoginResult> onLoginController = new StreamController<LoginResult>();
    // might not be necessary if you only need one listener at most
    Stream<LoginResult> _onLogin = onLoginController.stream.asBroadcastStream(); 
    Stream<LoginResult> get onLogin => _onLogin
    ...
    onLoginController.add(new LoginResult()
      ..success = isSuccess
      ..userName = 'someUser');
    

    Then you can use it like