A Connectable Observable does not start emitting items when subscribed to; it only begins emitting when the Connect() method is called. This allows multiple observers to subscribe before data starts flowing. Connectable Observables also publish items, meaning all observers receive a copy of the same items.
To create one, use rxgo.WithPublishStrategy() with an operator like FromChannel.
Connect() returns a disposed channel and a cancel function to manage the subscription lifecycle.
ch := make(chan rxgo.Item)
go func() {
ch <- rxgo.Of(1)
ch <- rxgo.Of(2)
ch <- rxgo.Of(3)
close(ch)
}()
// Create a Connectable Observable
observable := rxgo.FromChannel(ch, rxgo.WithPublishStrategy())
observable.DoOnNext(func(i interface{}) {
fmt.Printf("First observer: %d\n", i)
})
observable.DoOnNext(func(i interface{}) {
fmt.Printf("Second observer: %d\n", i)
})
disposed, cancel := observable.Connect()
go func() {
time.Sleep(time.Second)
cancel()
}()
<-disposed