How can i make a new stream of other streams returning a list of all the values emitted (bloc pattern)?

别来无恙 提交于 2021-01-29 10:40:15

问题


I have three streams like this:

  final _light1RoomCtlr = BehaviorSubject<String>();
  final _light2RoomCtlr = BehaviorSubject<String>();
  final _light3RoomCtlr = BehaviorSubject<String>();
  Stream<String> get getLight1Room => _light1RoomCtlr.stream;
  Function(String) get setLight1Room => _light1RoomCtlr.sink.add;
  Stream<String> get getLight2Room => _light2RoomCtlr.stream;
  Function(String) get setLight2Room => _light2RoomCtlr.sink.add;
  Stream<String> get getLight3Room => _light3RoomCtlr.stream;
  Function(String) get setLight3Room => _light3RoomCtlr.sink.add;

I want to merge them all so i can get all the values emitted when i need it.

The thing is.. i am using bloc pattern and i don't have a initState() function on it, so i can't initialize stuff.. so dart won't let me do something like this on the same file:

 final List<String> _lightRooms = List<String>();
  Observable.merge([getLight1Room, getLight2Room, getLight3Room]).listen((room) =>
    _lightRooms.add(room);
  ));

I have tried a lot of things and i keep getting the error message: only static members are initializable.. or something like that.. How can i procede this using reactive programming and bloc pattern? If i do the listening on a widget that i need it, i can lose the info on another one. i tried rxjs examples but here it does not work since this is only class definition things.


回答1:


You can user combineLatest2, combineLatest4, combineLatest5 and so on

for example:

import 'dart:async';

import 'package:login_bloc/src/blocs/validators.dart';
import 'package:rxdart/rxdart.dart';

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

  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);

  Function(String) get changeEmail => _email.sink.add;
  Function(String) get changePassword => _password.sink.add;

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

    print('valid data:');
    print(validEmail);
    print(validPassword);
  }

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


来源:https://stackoverflow.com/questions/55951503/how-can-i-make-a-new-stream-of-other-streams-returning-a-list-of-all-the-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!