-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubscription.go
More file actions
205 lines (171 loc) · 5.32 KB
/
subscription.go
File metadata and controls
205 lines (171 loc) · 5.32 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright 2025 samber.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/samber/ro/blob/main/licenses/LICENSE.apache.md
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ro
import (
"sync"
"github.com/samber/lo"
"github.com/samber/ro/internal/xerrors"
)
// Teardown is a function that cleans up resources, such as closing
// a file or a network connection. It is called when the Subscription is closed.
// It is part of a Subscription, and is returned by the Observable creation.
// It will be called only once, when the Subscription is canceled.
type Teardown func()
// Unsubscribable represents any type that can be unsubscribed from.
// It provides a common interface for cancellation operations.
type Unsubscribable interface {
Unsubscribe()
}
// Subscription represents an ongoing execution of an `Observable`, and has
// a minimal API which allows you to cancel that execution.
type Subscription interface {
Unsubscribable
Add(teardown Teardown)
AddUnsubscribable(unsubscribable Unsubscribable)
IsClosed() bool
Wait() // Note: using .Wait() is not recommended.
}
var _ Subscription = (*subscriptionImpl)(nil)
// NewSubscription creates a new Subscription. When `teardown` is nil, nothing
// is added. When the subscription is already disposed, the `teardown` callback
// is triggered immediately.
func NewSubscription(teardown Teardown) Subscription {
teardowns := make([]func(), 0, 4) // Pre-allocate for common case
if teardown != nil {
teardowns = append(teardowns, teardown)
}
return &subscriptionImpl{
done: false,
mu: sync.Mutex{},
finalizers: teardowns,
}
}
type subscriptionImpl struct {
done bool
mu sync.Mutex // Should be a RWMutex because of the .IsClosed() method, but sync.RWMutex is 30% slower.
finalizers []func()
}
// Add receives a finalizer to execute upon unsubscription. When `teardown`
// is nil, nothing is added. When the subscription is already disposed, the `teardown`
// callback is triggered immediately.
//
// This method is thread-safe.
//
// Implements Subscription.
func (s *subscriptionImpl) Add(teardown Teardown) {
if teardown == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.done {
teardown() // not protected against panics
} else {
s.finalizers = append(s.finalizers, teardown)
}
}
// AddUnsubscribable merges multiple subscriptions into one. The method does nothing
// if `unsubscribable` is nil.
//
// This method is thread-safe.
//
// Implements Subscription.
func (s *subscriptionImpl) AddUnsubscribable(unsubscribable Unsubscribable) {
if unsubscribable == nil {
return
}
s.Add(unsubscribable.Unsubscribe)
}
// Unsubscribe disposes the resources held by the subscription. May, for
// instance, cancel an ongoing `Observable` execution or cancel any other
// type of work that started when the `Subscription` was created.
//
// This method is thread-safe. Finalizers are executed in sequence.
//
// Implements Unsuscribable.
func (s *subscriptionImpl) Unsubscribe() {
s.mu.Lock()
if s.done {
s.mu.Unlock()
return
}
s.done = true
if len(s.finalizers) == 0 {
s.mu.Unlock()
return
}
finalizers := s.finalizers
s.finalizers = make([]func(), 0)
s.mu.Unlock()
var errs []error
// Note: we prefer not running this in parallel.
for i := range finalizers {
err := execFinalizer(finalizers[i]) // protected against panics
if err != nil {
// OnUnhandledError(err)
errs = append(errs, err)
}
}
// Error is triggered after the recursive call to finalizers
// because we want to execute all finalizers before panicking.
if len(errs) > 0 {
// errors.Join has been introduced in go 1.20
panic(xerrors.Join(errs...))
}
}
// IsClosed returns true if the subscription has been disposed
// or if unsubscription is in progress.
//
// Implements Subscription.
func (s *subscriptionImpl) IsClosed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.done
}
// Wait blocks until a `Subscription` is canceled. It can be used for
// blocking until an `Observable` throws an error or completes.
//
// Please use it carefully. Calling this method is against the Reactive
// Programming Manifesto. This method might be deleted in the future.
//
// Note: using .Wait() is not recommended.
//
// Implements Subscription.
func (s *subscriptionImpl) Wait() {
ch := make(chan struct{}, 1)
// There is no guarantee that this callback will be the last finalizer
// added to this subscription.
s.Add(func() {
ch <- struct{}{}
})
<-ch
close(ch)
}
// execFinalizer runs the finalizer and catches any panics, converting them to errors.
func execFinalizer(finalizer func()) (err error) {
lo.TryCatchWithErrorValue(
func() error {
finalizer()
err = nil
return nil
},
func(e any) {
err = newUnsubscriptionError(recoverValueToError(e))
},
)
return err
}
// @TODO: Add methods Remove + RemoveSubscription.
// Currently, Go does not support function address comparison, so we cannot
// remove a finalizer from the list.