How to extract Left or Right easily from Either type in Dart (Dartz)

后端 未结 3 566
抹茶落季
抹茶落季 2021-02-04 09:53

I am looking to extract a value easily from a method that return a type Either.

I am doing some tests but unable to test easily th

相关标签:
3条回答
  • 2021-02-04 10:25
      Future<Either<Failure, FactsBase>> call(Params params) async {
    final resulting = await repository.facts();
    return resulting.fold(
      (failure) {
        return Left(failure);
      },
      (factsbase) {
        DateTime cfend = sl<EndDateSetting>().finish;        
        List<CashAction> actions = factsbase.transfers.process(facts: factsbase, startDate: repository.today, finishDate: cfend); // process all the transfers in one line using extensions
        actions.addAll(factsbase.transactions.process(facts: factsbase, startDate: repository.today, finishDate: cfend));
        for(var action in actions) action.account.cashActions.add(action); // copy all the CashActions to the Account.
        for(var account in factsbase.accounts) account.process(start: repository.today);
        return Right(factsbase);
      },
    );
    

    }

    0 讨论(0)
  • 2021-02-04 10:39

    Ok here the solutions of my problems:

    To extract/retrieve the data

    final Either<ServerException, TokenModel> result = await repository.getToken(...);
    result.fold(
     (exception) => DoWhatYouWantWithException, 
     (tokenModel) => DoWhatYouWantWithModel
    );
    
    //Other way to 'extract' the data
    if (result.isRight()) {
      final TokenModel tokenModel = result.getOrElse(null);
    }
    

    To test the exception

    //You can extract it from below, or test it directly with the type
    expect(() => result, throwsA(isInstanceOf<ServerException>()));
    
    0 讨论(0)
  • 2021-02-04 10:48

    I can't post a comment... But maybe you could look at this post. It's not the same language, but looks like it's the same behaviour.

    Good luck.

    0 讨论(0)
提交回复
热议问题