This repository was archived by the owner on Mar 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathsearch.go
72 lines (64 loc) · 1.42 KB
/
search.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package mobile
import (
"github.com/segmentio/ksuid"
"github.com/textileio/go-textile/broadcast"
"github.com/textileio/go-textile/pb"
)
// SearchHandle is used to cancel an async search request
type SearchHandle struct {
Id string
cancel *broadcast.Broadcaster
done func()
}
// Cancel is used to cancel the request
func (h *SearchHandle) Cancel() {
h.cancel.Close()
h.done()
}
// handleSearchStream handles the response channels from a search
func (m *Mobile) handleSearchStream(resultCh <-chan *pb.QueryResult, errCh <-chan error, cancel *broadcast.Broadcaster) (*SearchHandle, error) {
id := ksuid.New().String()
var done bool
doneFn := func() {
if done {
return
}
done = true
m.notify(pb.MobileEventType_QUERY_RESPONSE, &pb.MobileQueryEvent{
Id: id,
Type: pb.MobileQueryEvent_DONE,
})
}
handle := &SearchHandle{
Id: id,
cancel: cancel,
done: doneFn,
}
go func() {
for {
select {
case err := <-errCh:
m.notify(pb.MobileEventType_QUERY_RESPONSE, &pb.MobileQueryEvent{
Id: id,
Type: pb.MobileQueryEvent_ERROR,
Error: &pb.Error{
Code: 500,
Message: err.Error(),
},
})
return
case res, ok := <-resultCh:
if !ok {
doneFn()
return
}
m.notify(pb.MobileEventType_QUERY_RESPONSE, &pb.MobileQueryEvent{
Id: id,
Type: pb.MobileQueryEvent_DATA,
Data: res,
})
}
}
}()
return handle, nil
}