Skip to content

Commit

Permalink
Factor out generic state listener
Browse files Browse the repository at this point in the history
  • Loading branch information
kegsay committed Feb 14, 2024
1 parent 5ad6847 commit 7c287df
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 23 deletions.
2 changes: 2 additions & 0 deletions internal/api/rust/dynamic_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"golang.org/x/exp/slices"
)

// This is a recurring pattern in the FFI bindings where a room list or timeline has delta updates
// sent to it. Rather than reimplementing all the functions over and over, define it once here.
type DynamicSlice[T any] struct {
Slice []T
}
Expand Down
28 changes: 28 additions & 0 deletions internal/api/rust/generic_state_listener.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package rust

// This is a recurring pattern in the ffi bindings, where a param is an interface
// which has a single OnUpdate(T) method. Rather than having many specific impls,
// just have a generic one which can be listened to via a channel. Using a channel
// means we can time out more easily using select {}.
type genericStateListener[T any] struct {
ch chan T
isClosed bool
}

func newGenericStateListener[T any]() *genericStateListener[T] {
return &genericStateListener[T]{
ch: make(chan T),
}
}

func (l *genericStateListener[T]) Close() {
l.isClosed = true
close(l.ch)
}

func (l *genericStateListener[T]) OnUpdate(state T) {
if l.isClosed {
return
}
l.ch <- state
}
2 changes: 2 additions & 0 deletions internal/api/rust/room_listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"sync/atomic"
)

// This is a more ergonomic way to listen for updates from the FFI layer, as it will allow you to listen
// for non-existing rooms without crashing.
type RoomsListener struct {
listeners map[int32]func(roomID string) (cancel bool)
listenerID atomic.Int32
Expand Down
23 changes: 0 additions & 23 deletions internal/api/rust/rust.go
Original file line number Diff line number Diff line change
Expand Up @@ -729,26 +729,3 @@ func eventTimelineItemToEvent(item *matrix_sdk_ffi.EventTimelineItem) *api.Event
}
return &complementEvent
}

type genericStateListener[T any] struct {
ch chan T
isClosed bool
}

func newGenericStateListener[T any]() *genericStateListener[T] {
return &genericStateListener[T]{
ch: make(chan T),
}
}

func (l *genericStateListener[T]) Close() {
l.isClosed = true
close(l.ch)
}

func (l *genericStateListener[T]) OnUpdate(state T) {
if l.isClosed {
return
}
l.ch <- state
}

0 comments on commit 7c287df

Please sign in to comment.