Search code examples
dartfluttergoogleio

How to make a Sink<Locale> to format the result of a Stream<String>?


In google IO 18, the Flutter presenters have showed a feature but have not showed how to implement this. The video (at exact time) is: https://youtu.be/RS36gBEp8OI?t=1776

How to implement such thing? How can I properly make the Stream to be correctly formatted based on a Sink?

(sorry but I am not too familiar with Rx)


Solution

  • Use the combineLatest function from the rxdart package. It takes the latest values of input streams, so any time either the locale or cart items change it will calculate and format the total cost.

    import 'dart:async'; // Sink, Stream
    import 'dart:ui'; // Locale
    import 'package:rxdart/rxdart.dart'; // Observable, *Subject
    
    class Bloc {
      var _locale = BehaviorSubject<Locale>(seedValue: Locale('en', 'US'));
      var _items = BehaviorSubject<List<CartItem>>(seedValue: []);
      Stream<String> _totalCost;
    
      Sink<Locale> get locale => _locale.sink;
      Stream<List<CartItem>> get items => _items.stream;
      Stream<String> get totalCost => _totalCost;
    
      Bloc() {
        _totalCost = Observable.combineLatest2<Locale, List<CartItem>, String>(
            _locale, _items, (locale, items) {
          // TODO calculate total price of items and format based on locale
          return 'USD 10.00';
        }).asBroadcastStream();
      }
    
      void dispose() {
        _locale.close();
        _items.close();
      }
    }
    

    Disclaimer: I didn't try to run this code so there might be errors but the basic idea should be solid.