RxDart. Listener of BehaviorSubject does not get value after subject.add(value)

Issue

I have two classes: CurrencyRepo and CurrencyFetcher. From CurrencyFetcher I try to listen to the behaviorSubject that is in the repo. But when I add values in the behaviorSubject inside the repo, CurrencyFetcher does not get these values. What am I doing wrong?

class CurrencyFetcher implements CurrencyFetcherService {
  final CurrencyRepo _currencyRepo;
  StreamSubscription currencySubscription;

  CurrencyFetcher(this._currencyRepo, this._preferencesService) {
    _subscribeToCurrencies();
  }

  void _subscribeToCurrencies() {
    currencySubscription = _currencyRepo
        .getCurrenciesStream()
        .listen((currencies) => _handleApiCurrencies);
  }

  Future<void> _handleApiCurrencies(List<ApiCurrency> apiCurrencies) async {
  // implemetation
  }
}
class CurrencyRepo {
  final CurrencyApi _currencyApi;
  final BehaviorSubject<List<ApiCurrency>> _currencySubject = BehaviorSubject.seeded([]);

  Stream<List<ApiCurrency>> getCurrenciesStream() {
    _updateCurrencies();
    return _currencySubject.stream;
  }

  CurrencyRepo(this._currencyApi);

  void _updateCurrencies() {
    _currencyApi.getCurrencies().then((currencies) {
      _currencySubject.add(currencies);
    });
  }
}

I have checked that the values are added to the stream after the CurrencyFetcher starts to listen. And I have checked that in the moment, when I add new value to the stream, it has a listener. The first time using RxDart, may someone help? 🙂

Solution

Inside the function _subscribeToCurrencies() try to write

_currencyRepo.currenciesStream.listen((currencies) {
      _handleApiCurrencies(currencies);
});

instead of

_currencyRepo.currenciesStream.listen(_handleApiCurrencies);

Answered By – Maksym Omelchenko

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *