패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.5.0

reselect

Redux 스토어에서 데이터를 효율적으로 파생시키기

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
6.4천
좋아요
19
Pub 점수
140

패키지 설치

flutter pub add reselect

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Redux 스토어에서 데이터를 효율적으로 파생하기 위한 reselect 라이브러리의 Dart 구현입니다. 입력 종속성이 변경될 때만 재계산되는 메모이제이션된 선택자를 가능하게 하여 반응형 UI의 성능을 향상시킵니다. 파생된 데이터가 자주 액세스되지만 불필요한 재구성은 유발하지 않아야 하는 복잡한 상태 로직에 이상적입니다. 패키지는 Flutter의 Redux 생태계와 원활하게 통합되며 모든 주요 플랫폼을 지원합니다.

사용 사례

  • 대규모 Redux 스토어에서 파생 상태 최적화
  • 불필요한 위젯 재구성 줄이기
  • 재사용 가능하고 조합 가능한 선택자 만들기
  • 데이터 집약형 앱의 성능 향상
  • 복잡한 상태 전환 관리
  • 비용이 큰 계산 캐싱

주요 기능

  • 메모이제이션된 선택자
  • 입력 종속성 추적
  • 조합 가능한 선택자 함수
  • 최소의 런타임 오버헤드
  • 비동기 선택자 지원
  • 크로스 플랫폼 호환성

적합한 대상

  • 상태 관리에 Redux를 사용하는 앱
  • 성능 최적화를 찾는 개발자
  • 자주 상태를 파생하는 프로젝트
  • 클린하고 유지보수 가능한 상태 로직을 우선시하는 팀
  • 복잡한 UI 상태를 가진 Flutter 애플리케이션

고려 사항

  • Redux 통합 필요
  • 신규 사용자를 위한 학습 곡선
  • Redux 기반 아키텍처에 한정
  • 간단한 상태 요구 사항에 적합하지 않습니다
  • 작은 프로젝트에 복잡성을 추가할 수 있음
  • 외부 Redux 설정에 의존합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Reselect for Dart

Build Status codecov

A Selector library for Dart, based on the original Reselect JavaScript library.

  • Selectors are functions that derive data from a single input, such as a the State of a Redux Store.
  • Selectors can expose a single point of entry to the data in your Redux Store
  • Selectors can compute derived data, allowing Redux to store the minimal possible state.
  • Selectors are efficient. Derived data is not recomputed unless one of its arguments change.
  • Selectors are composable. They can be combined to create more complex selectors.

Note: This library and examples are geared toward Redux, but can really work with any Redux implementation or data source.

Installation

See the instructions on the package page: https://pub.dartlang.org/packages/reselect#pub-pkg-tab-installing

Example

Motivation

Let's set up a simple Redux example to explain our motivation. In our case, we'll have an AppState that holds a list of Products and the name of our Shop. We want to show a screen that displays a list of all products that are On Sale. We'll also need another page that filters products to those that are less expensive that $10 (or euros or yuan, ya know).

Let's see the simplest way we can do this!

// Start with a Product class
class Product {
  String name;
  bool onSale;
  double price;

  Product(this.name, this.price, [this.onSale = false]);

  // A helper constructor for creating On Sale items
  factory Product.onSale(String name, double price) => new Product(
    name,
    price,
    true,
  );
}

// Create a class that holds the State of our app.
class AppState {
  final String shopName;
  final List<Product> products;

  AppState(this.shopName, this.products);
}

// Create your app state at some point in your app
final appState = new AppState("Brian's Keyboard Stop", [
  new Product("Cherry Mx Red switch", 14.99),
  new Product("Cherry Mx Blue switch", 9.99),
  new Product.onSale("Cherry Mx Brown switch", 8.99),
]);

// Create a function that finds which products are on sale
final selectOnSaleProduct = (AppState state) =>
    state.products.where((product) => product.onSale);

// Also create a function that finds the products that are under $10
final affordableProductsSelector = (AppState state) =>
    state.products.where((product) => product.price < 10.00);

So far, so good. Honestly, for small apps, don't go any further than this. Don't import this library, and just write some nice and simple functions. They're great just as they are!

Create a Single Point of Access

Now, instead of 2 functions that need to derive data from the products, say you had 10-20. This is fine as long as the AppState stays the same, but what if the AppState changes, and the list of Products moves to a different place in the State tree?

The first improvement we can make is to create a function that "selects" the products from your app state, so if any changes are made to the State, one function alone needs to be changed. Then, all of your functions that need the list of products can use this function as a single point of access.

This example continues from the previous code.

// Now, you can write a selector (remember, just a normal function),
// that finds the products in your AppState. This should be used as the
// single point of access to the products in your State.
final productsSelector = (AppState state) => state.products;

// Example usage. This will print the list of products in the AppState.
print(productsSelector(appState));

// Now, we'll update our previous selector functions to use this single
// point of access.
final selectOnSaleProduct = (AppState state) =>
    productsSelector(state).where((product) => product.onSale);

// Also create a function that finds the products that are under $10
final affordableProductsSelector = (AppState state) =>
    productsSelector(state).where((product) => product.price < 10.00);

You might notice that we're not doing anything special so far, nor are we even using the library! But we have made our code a bit more robust.

Memoizing Computed Values

Now, let's actually use this library! Selecting part of your State tree can be handy, and requires nothing special, but we can go further. Say you need to derive some data, such as the list of products that are on sale, but to do so is expensive (perhaps there are thousands and thousands of Products in your AppState). In this case, it might be nice to cache (aka memoize) the result and only recompute the result when the inputs change.

This is exactly what the createSelector1 to createSelector10 functions contained in this library are for. These functions combine 1 to 10 selectors together into one new memoized selector.

Let's continue from our previous example.

// This example will compute all products that are on sale only when
// the list of products changes, which it gets from the productsSelector.
final onSaleSelector = createSelector1(
  productsSelector,
  (products) => products.where((product) => product.onSale),
);

// Also memoize the function that finds the products that are under $10
final affordableProductsSelector = createSelector1(
    productsSelector,
    (products) => products.where((product) => product.price < 10.00),
);

// Example usage. This will print the list of all products on Sale
print(onSaleSelector(appState));

// If we try printing again, the onSaleSelector will check if the
// products have changed, and since they have not, will return the
// cached result!
print(onSaleSelector(appState));
Combining Selectors

Cool, so now we've got a couple of memoized Selectors (functions) that only recompute their values when the underlying data changes! Now let's start putting them together like Legos.

Say you now want to create a "Snap Deals" page that shows all on sale products AND all products under $10. We can combine our two memoized selectors from the previous example to create this new selector!

// We'll use `createSelector2` to combine 2 selectors with a given function.
// In this case, we'll combine the onSaleSelector and the
// affordableProductsSelector from our previous example into a new list
// containing all of these products.
final snapDealsSelector = createSelector2(
  onSaleSelector,
  affordableProductsSelector,
  (onSaleProducts, affordableProducts) =>
      ([]..addAll(onSaleProducts)..addAll(affordableProducts)),
);
Review

Ok, so now that we've covered a decent amount of ground, let's summarize:

  • We've gone from directly accessing the Products contained within the AppState to using a selector (function) that acts as single point of access
  • Memoized our expensive selectors (using createSelector1) so they don't recompute unless the data they depend on has changed.
  • Combined those 2 memoized selectors (using createSelector2) into a new memoized selector! How deep can you go!?!?!

So that's about it. That's why you'd use this library and the story of how you can create more helpful abstractions along the way, even without including this library!

Extras

Changing the memoization

The default memoize functions come from the memoize package. They use the == method of your arguments to determine whether or not your input values have changed. Most of the time, properly implementing == on your classes is the way to go, but if you need to change how it works, you can supply your own memoize function.

The following example will use it's own custom memoize function. A memoize function takes in a function and returns a function of the same signature. It is responsible for handling how it caches the resulting values.

// This time, we'll write the same onSaleSelector, but provide
// our own memoize function that will compare the inputs by Identity
// rather than by using the `==` method!
final onSaleSelector = createSelector1(
  productsSelector,
  // This second function is called the combiner. It's the function
  // that needs to be memoized!
  (products) => products.where((product) => product.onSale),

  // The memoize function takes in the combiner (where all the expensive
  // computations take place), and returns a new, memoized combiner
  // function!
  //
  // Try not to get scared by the type signature -- the combiner is
  // simply a function that takes in a list of Products, and returns a
  // list of Products.
  memoize: (Func1<List<Product>, List<Product>> combiner) {
    List<Product> prevProductsArg;
    List<Product> prevOnSaleProducts;

    return ((List<Product> productsArg) {
      // Use `identical` instead of `==` for comparing arguments
      if (identical(productsArg, prevProductsArg)) {
        return prevOnSaleProducts;
      } else {
        prevProductsArg = productsArg;
        prevOnSaleProducts = combiner(arg);

        return prevOnSaleProducts;
    });
  },
);
Selectors with arguments

To create a selector which takes arguments, you have a few options. First, you can write a fuction that creates a selector. Let's say you wanted to make the affordable products selector configurable:

Selector<AppState, List<Product>> createAffordableProductsSelector(double price) {
  return createSelector1(
    productsSelector,
      (products) => products.where((product) => product.price < price),
    );
}

// Usage
final affordableProductsSelector = createAffordableProductsSelector(10.00);
final affordableProducts = affordableProductsSelector(appState);

The other option: Although a selector only takes in 1 parameter, that parameter can be anything you want. It can be a class that holds multiple values, or a Dart 3 record.

typedef Params = (AppState state, double price);

final affordableProductsSelector = createSelector1<Params, (List<Product>, double), List<Product>>(
    (params) => (productsSelector(params.$1), params.$2),
    (result) => result.$1.where((product) => product.price < result.$2),
);

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트