Git Product home page Git Product logo

rx_notifier's Introduction

rx_notifier

The ValueNotifier é uma forma simples e nativa de reatividade do Flutter. Esta extension visa aplicar de forma transparente a functional reactive programming (TFRP).

Install

Add in pubspec.yaml:

dependencies:
  rx_notifier: <version>

Entendendo a Extensão.

Está extensão acrescenta uma classe RxNotifier e um conversor ValueNotifier -> RxNotifier para que possa ser observado de forma transparente pela função rxObserver() e pelo Widget RxBuilder.

O RxNotifier é diretamente uma extensão de ValueListenable então qualquer objeto que o implemente pode ser convertido para RxNotifier

A única diferença do RxNofifier para o ValueNotifier é a função de assinatura automática nos Observadores rxObserver() e RxBuilder, muito semelhante as reactions do MobX.

Using

Para começar instancie um RxNofifier.

final counter = RxNotifier<int>(0);

ou converta um ValueNotifier já existente usando o método .rx():

final counter = myValueNotifierCounter.rx();

IMPORTANT: O método rx() foi adicionado ao ValueNotifier usando Extension Methods.

Atribuímos um novo valor:

final counter = RxNotifier<int>(0);

increment(){
    counter.value++;
}

E escutamos as alterações usando o rxObserver:

RxDisposer disposer = rxObserver((){
    print(counter.value);
});


disposer();

Ou escutamos na árvore de Widget usando o RxBuilder:

Widget builder(BuildContext context){
    return RxBuilder(
        builder: (_) => Text('${counter.value}'),
    );
}

Esse é o uso transparente de reatividade individual, porém podemos também combinar RxNotifier Objects produzindo um novo valor. Essa técnica se chama Computed

Computed: Combinando valores reativos

Para combinar dois ou mais RxNotifier Objects precisamos usar um getter retornando um novo valor combinado:

final num1 = RxNotifier<int>(1);
final num2 = RxNotifier<int>(2);

String get result => 'num1: ${num1.value} + num2: ${num2.value} = ${num1.value + num2.value}';

...

rxObserver((){
    print(result); // print´s "num1: 1 + num2: 2 = 3
});

IMPORTANT: É realmente necessário que os computed sejam Getters e não atribuições. A reação acontecerá quando qualquer um dos RxNotifier modificar o valor.

Usando Getters

Podemos também usar getters nos valores reativos tornando, vamos repetir o exemplo acima:

final _num1 = RxNotifier<int>(1);
int get num1 => _num1.value;

final _num2 = RxNotifier<int>(2);
int get num2 => _num2.value;

String get result => 'num1: $num1 + num2: $num2 = ${num1 + num2}';

...

rxObserver((){
    print(result); // print´s "num1: 1 + num2: 2 = 3
});

Filtros

Tanto o rxObserver quanto o RxBuilder tem a propriedade filter que é uma função que retorna um bool. Use isso para definir quando(ou não) refletir as alterações:

Widget builder(BuildContext context){
    return RxBuilder(
        filter: () => counter.value < 10,
        builder: (_) => Text('${counter.value}'),
    );
}

Potencialize mais o ValueNotifier

O functional_listener adiciona map, where, listen, debounce, combineLatest e várias outras funções para o ValueNotifier. Muito obrigado Thomas Burkhart por isso!!!

Features and bugs

Please send feature requests and bugs at the issue tracker.

This README was created based on templates made available by Stagehand under a BSD-style license.

rx_notifier's People

Contributors

jacobaraujo7 avatar orlandoeduardo101 avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.