417304 (2) [Avatar] Offline
#1
I don’t understand the sample from Listing 7.9

var connectableObservable = Observable.Defer(() => ChatServer.Current.ObserveMessages()).Publish();

As I understand it right Publish allow to connect to one source and give all subscribes same data and data will be get after the call to Connect.
If this is true what is the purpose of Defer – it should delay getting the data till first subscription but subscription should be done in Connect so it is already deferred – Where I’m getting this wrong?
Tamir Dresher (35) [Avatar] Offline
#2
When you "Connect" the ConnectableObservable, the subscription to the underlying observable will take place, and from that moment all the subscribers will start to receive the notifications.
But if the underlying observable was already hot, like in the case of ChatServer.Current.ObserveMessages() all the notification that were emitted before the call to Connect are lost.
Defer will only execute the factory method we pass to it when the observer subscribes. So in this case we will only connect to the ChatServer and start receiving messages after we subscribed all the subscribers and no message will be lost.



417304 (2) [Avatar] Offline
#3
defer.png
[ 4 KB ]
Sorry but it is still not clear to me. I have attached some image to illustrate the way I'm seeing this. Messages are generated in hot manner and we are connecting to it. Let assume for start that we are only using Publish without Defer. Then like on the image we are connecting observer A and observer B and finally execute Connect - after this every message after connect (E, F...) will be transferred to observers and messages A, B, C, D will be lost. As you describe in paragraph about Publish it assures that everyone have same set of messages but I can't see how defer will make that no message will be lost? When I was tested the behavior with or without Defer is the same but Maybe because I still don't get it right?