Skip to content

Commit

Permalink
Item utility functions
Browse files Browse the repository at this point in the history
  • Loading branch information
teivah committed Feb 17, 2020
1 parent 70d2d0e commit ece66e9
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 21 deletions.
53 changes: 53 additions & 0 deletions item.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package rxgo

import "context"

type (
// Item is a wrapper having either a value or an error.
Item struct {
V interface{}
E error
}
)

// Of creates an item from a value.
func Of(i interface{}) Item {
return Item{V: i}
}

// Error creates an item from an error.
func Error(err error) Item {
return Item{E: err}
}

// Error checks if an item is an error.
func (i Item) Error() bool {
return i.E != nil
}

// SendBlocking sends an item and blocks until it is sent.
func (i Item) SendBlocking(ch chan<- Item) {
ch <- i
}

// SendContext sends an item and blocks until it is sent or a context canceled.
// It returns a boolean to indicate whether the item was sent.
func (i Item) SendContext(ctx context.Context, ch chan<- Item) bool {
select {
case <-ctx.Done():
return false
case ch <- i:
return true
}
}

// SendNonBlocking sends an item without blocking.
// It returns a boolean to indicate whether the item was sent.
func (i Item) SendNonBlocking(ch chan<- Item) bool {
select {
default:
return false
case ch <- i:
return true
}
}
29 changes: 29 additions & 0 deletions item_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package rxgo

import (
"context"
"github.com/stretchr/testify/assert"
"testing"
)

func Test_Item_SendBlocking(t *testing.T) {
ch := make(chan Item, 1)
defer close(ch)
Of(5).SendBlocking(ch)
assert.Equal(t, 5, (<-ch).V)
}

func Test_Item_SendContext_True(t *testing.T) {
ch := make(chan Item, 1)
defer close(ch)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
assert.True(t, Of(5).SendContext(ctx, ch))
}

func Test_Item_SendNonBlocking(t *testing.T) {
ch := make(chan Item, 1)
defer close(ch)
assert.True(t, Of(5).SendNonBlocking(ch))
assert.False(t, Of(5).SendNonBlocking(ch))
}
21 changes: 0 additions & 21 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,6 @@ type (

operatorItem func(ctx context.Context, item Item, dst chan<- Item, operator operatorOptions)
operatorEnd func(ctx context.Context, dst chan<- Item)

// Item is a wrapper having either a value or an error.
Item struct {
V interface{}
E error
}
)

const (
Expand All @@ -62,18 +56,3 @@ const (
// Drop drops the message.
Drop
)

// Error checks if an item is an error.
func (i Item) Error() bool {
return i.E != nil
}

// Of creates an item from a value.
func Of(i interface{}) Item {
return Item{V: i}
}

// Error creates an item from an error.
func Error(err error) Item {
return Item{E: err}
}

0 comments on commit ece66e9

Please sign in to comment.