Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inherit an store implementation acts like a kind of singleton #1000

Open
edcogue opened this issue Jun 2, 2024 · 0 comments
Open

Inherit an store implementation acts like a kind of singleton #1000

edcogue opened this issue Jun 2, 2024 · 0 comments

Comments

@edcogue
Copy link

edcogue commented Jun 2, 2024

I want to use an Store implementation like this

import 'package:mobx/mobx.dart';
part 'parent_controller.g.dart';

abstract class ParentStore = _ParentStore
    with _$ParentStore;

abstract class _ParentStore with Store {
  @observable
  ObservableList<String> someInfoList = emptyList;

  static ObservableList<String> emptyList = ObservableList.of([]);

  @observable
  ObservableFuture<List<String>> fetchInfoFuture = emptyResponse;

  @computed
  bool get hasResults =>
      fetchInfoFuture != emptyResponse &&
          fetchInfoFuture.status == FutureStatus.fulfilled ||
      someInfoList.isNotEmpty;

  static ObservableFuture<List<String>> emptyResponse =
      ObservableFuture.value([]);

  @action
  Future<void> fetchAndFollow() async {
    if (fetchInfoFuture.status == FutureStatus.pending) return;

    final future = fetch();
    fetchInfoFuture = ObservableFuture(future);

    final newInfo = await future;

    newInfo.map((e) => someInfoList.add(e));
  }

  Future<List<String>> fetch();
}

To implement the remaining abstract method fetch this way in another controller to reuse the previous code

import 'package:test/parent_controller.dart';

class ChildStore extends ParentStore {
  SomeRepo repo =  SomeRepo();

  @override
  Future<List<String>> fetch() async {
    final info = await repo.getAll();
    return info;
  }
}
import 'package:test/parent_controller.dart';

class OtherChildStore extends ParentStore {

  @override
  Future<List<String>> fetch() async {
    return [];
  }
}

When I use the ChildStore and OtherChildStore with different fetch methods, it seems that the data is store in a singleton, because no matter which is the implementation of fetch, all provide the same data. Is it possible to achieve this behavior?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant