Pull to refresh

Comments 4

Я не пишу на Dart, но почему бы добавить метод, который будет принимать две лямбды (для left и right частей) и вызывать одну из них?
Чтобы выглядело не так:


if (either.isRight) {
    final contact = either.right;
    yield ContactIsShowingState(contact);
} else {
    final failure = either.left;
    if (failure is NetworkFailure) yield NetworkFailureState(failure);
    if (failure is UnknownFailure) yield UnknownFailureState(failure);
}

А как-то так:


either.foreach(
    contact => { yield ContactIsShowingState(contact) },
    failure => {
        if (failure is NetworkFailure) yield NetworkFailureState(failure);
        if (failure is UnknownFailure) yield UnknownFailureState(failure);
    }
)
Из лямбды нельзя выполнить yield.
Там где это возможно, можно использовать метод «either», принимающий две функции и написать что-то вроде этого:

getUserEither.either((ServerError error) {
      print("Error: ${error.code}");
    }, (User user) {
      print("User: ${user.name}");
    });

А почему бы тогда не сделать так:


T either<T>(T Function(L) fnL, T Function(R) fnR) {
  if (isLeft) {
    final left = this as Left<L, R>;
    return fnL(left.value);
  }

  if (isRight) {
    final right = this as Right<L, R>;
    return fnR(right.value);
  }
}

и вызывать:


yield either.either(
    contact => ContactIsShowingState(contact),
    failure => {
        if (failure is NetworkFailure) return NetworkFailureState(failure);
        if (failure is UnknownFailure) return UnknownFailureState(failure);
    }
)
Sign up to leave a comment.

Articles