Skip to content

Add support for GetOrTrySetFunc #188

@blakearnold

Description

@blakearnold

I'm trying to set values using GetOrSetFunc, but sometimes there is a transient error when retrieving the value. This requires extra logic for handling an error.

Example:

	var err error
	result, _ := c.cachedBalance.GetOrSetFunc(
		pubkey, func() (balance *rpc.GetBalanceResult) {
			balance, err = c.rpcClient.GetBalance(ctx, accountID)
			return balance
		},
	)
	if err != nil {
                // delete from balance so it will be refetched next time
		c.cachedBalance.Delete(accountID)
		return nil, err
	}
	if result == nil || result.Value() == nil {
		return nil, fmt.Errorf("balance not found")
	}
	return result.Value(), nil

it would be nice to add a GetOrTrySetFunc so I can structure the code as so:

	var err error
	result, _ := c.cachedBalance.GetOrTrySetFunc(
		pubkey, func() (balance *rpc.GetBalanceResult, cancel bool) {
			balance, err = c.rpcClient.GetBalance(ctx, pubkey, rpc.CommitmentConfirmed)
			if err != nil {
				return nil, true
			}
			return balance, false
		},
	)
	if err != nil {
		return nil, err
	}
	return result.Value(), nil

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions