本文整理汇总了C#中Subject.AsObservable方法的典型用法代码示例。如果您正苦于以下问题:C# Subject.AsObservable方法的具体用法?C# Subject.AsObservable怎么用?C# Subject.AsObservable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Subject
的用法示例。
在下文中一共展示了Subject.AsObservable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
Subject<int> numbers = new Subject<int>();
var historicalScheduler = new System.Reactive.Concurrency.HistoricalScheduler(new DateTime(2015, 11, 21, 17, 10, 0));
historicalScheduler.Schedule(new DateTime(2015, 11, 21, 17, 10, 0), () => numbers.OnNext(1));
historicalScheduler.Schedule(new DateTime(2015, 11, 21, 17, 11, 0), () => numbers.OnNext(2));
historicalScheduler.Schedule(new DateTime(2015, 11, 21, 17, 32, 0), () => numbers.OnNext(3));
historicalScheduler.Schedule(new DateTime(2015, 11, 21, 17, 39, 0), () => numbers.OnNext(4));
historicalScheduler.Schedule(new DateTime(2015, 11, 21, 17, 51, 0), () => historicalScheduler.Stop());
numbers.AsObservable()
.Buffer(TimeSpan.FromMinutes(20), historicalScheduler)
.Subscribe(buffer =>
{
Console.WriteLine("time is: {0}", historicalScheduler.Now);
Console.WriteLine("Buffer:");
foreach (var x in buffer)
{
Console.WriteLine("\t{0}", x);
}
});
historicalScheduler.Start();
Console.WriteLine("Press <enter> to continue");
Console.ReadLine();
}
示例2: Run
public static async Task Run()
{
var s = new Subject<TestDisposable>();
var obs = s.AsObservable().AddRef();
// obs.Where(d => d.Id % 2 == 0).Subscribe(d => d.Write("Where Even"));
// obs.Where(d => d.Id % 2 == 1).Subscribe(d => d.Write("Where Odd"));
// obs.Skip(1).Take(2).Subscribe(d => d.Write("Skip Take"));
await Program.SwitchToCompute();
obs.Using().Skip(2).Take(2).ObserveOn(Program.Monitor).Subscribe(d =>
{
// using (d)
{
d.Write("Challenging Pre...");
// await Program.SwitchToCompute();
d.Write("Challenging Middle...");
// await Program.SwitchToRender();
d.Write("Challenging Post...");
}
}, () => Console.WriteLine("Challenging Completed"));
for (int i = 0; i < 8; ++i)
using (var d = new TestDisposable())
s.OnNext(d);
s.OnCompleted();
await TaskEx.Delay(30000);
if (Global.Yes)
return;
}
示例3: ProccessingTheSourceAndTheResult
private static void ProccessingTheSourceAndTheResult()
{
Demo.DisplayHeader("The SelectMany operator - with resultSelector you can ");
var roomsSubject = new Subject<ChatRoom>();
IObservable<ChatRoom> rooms = roomsSubject.AsObservable();
rooms
.Log("Rooms")
.SelectMany(r => r.Messages,
(room, msg) => new ChatMessageViewModel(msg) {Room = room.Id})
.Subscribe(vm => AddToDashboard(vm));
var room1 = new Subject<ChatMessage>();
roomsSubject.OnNext(new ChatRoom { Id = "Room1", Messages = room1 });
room1.OnNext(new ChatMessage { Content = "First Message", Sender = "1" });
room1.OnNext(new ChatMessage { Content = "Second Message", Sender = "1" });
var room2 = new Subject<ChatMessage>();
roomsSubject.OnNext(new ChatRoom { Id = "Room2", Messages = room2 });
room2.OnNext(new ChatMessage { Content = "Hello World", Sender = "2" });
room1.OnNext(new ChatMessage { Content = "Another Message", Sender = "1" });
}
示例4: FinallyTestCases
private static void FinallyTestCases()
{
Demo.DisplayHeader("The Finally operator - runs an action when the observable terminates, wither gracefully or due to an error");
Console.WriteLine();
Console.WriteLine("Successful complete");
Observable.Empty<int>()
.Finally(() => Console.WriteLine("Finally Code"))
.SubscribeConsole();
Console.WriteLine();
Console.WriteLine("Error termination");
Observable.Throw<Exception>(new Exception("error"))
.Finally(() => Console.WriteLine("Finally Code"))
.SubscribeConsole();
Console.WriteLine();
Console.WriteLine("Unsubscribing");
Subject<int> subject=new Subject<int>();
var subscription =
subject.AsObservable()
.Finally(() => Console.WriteLine("Finally Code"))
.SubscribeConsole();
subscription.Dispose();
}
示例5: FlatenningObservableOfObservables
private static void FlatenningObservableOfObservables()
{
Demo.DisplayHeader("The SelectMany operator - flattening observables of message to one stream of messages");
var roomsSubject = new Subject<ChatRoom>();
IObservable<ChatRoom> rooms = roomsSubject.AsObservable();
rooms
.Log("Rooms")
.SelectMany(r => r.Messages)
.Select(m => new ChatMessageViewModel(m))
.Subscribe(vm => AddToDashboard(vm));
//
// This is how the same example would look without SelectMany
//
//rooms
// .Log("Rooms")
// .Select(r => r.Messages)
// .Select(messages => messages.Select(m => new ChatMessageViewModel(m)))
// .Subscribe(roomMessages => roomMessages.Subscribe(m => AddToDashboard(m)));
var room1 = new Subject<ChatMessage>();
roomsSubject.OnNext(new ChatRoom {Id = "Room1", Messages = room1.Do(m => m.Room = "Room1")});
room1.OnNext(new ChatMessage {Content = "First Message", Sender = "1"});
room1.OnNext(new ChatMessage {Content = "Second Message", Sender = "1"});
var room2 = new Subject<ChatMessage>();
roomsSubject.OnNext(new ChatRoom {Id = "Room2", Messages = room2.Do(m => m.Room = "Room2")});
room2.OnNext(new ChatMessage {Content = "Hello World", Sender = "2"});
room1.OnNext(new ChatMessage {Content = "Another Message", Sender = "1"});
}
示例6: TcpSocketListenerPage
public TcpSocketListenerPage()
{
_listener = new TcpSocketListener();
_messagesSub = new Subject<Message>();
_messagesObs = _messagesSub.AsObservable();
_listener.ConnectionReceived += (sender, args) =>
{
var client = args.SocketClient;
Device.BeginInvokeOnMainThread(() => _clients.Add(client));
Task.Factory.StartNew(() =>
{
foreach (var msg in client.ReadStrings(_canceller.Token))
{
_messagesSub.OnNext(msg);
}
Device.BeginInvokeOnMainThread(()=> _clients.Remove(client));
}, TaskCreationOptions.LongRunning);
};
InitView();
}
示例7: UdpSocketClientPage
public UdpSocketClientPage()
{
_client = new UdpSocketClient();
_messagesSub = new Subject<Message>();
_messagesObs = _messagesSub.AsObservable();
InitView();
}
示例8: GroupJoin
private static void GroupJoin()
{
Demo.DisplayHeader("The GroupJoin operator - correlates elements from two observables based on overlapping duration windows and put them in a correlation group");
Subject<DoorOpened> doorOpenedSubject = new Subject<DoorOpened>();
IObservable<DoorOpened> doorOpened = doorOpenedSubject.AsObservable();
var enterences = doorOpened.Where(o => o.Direction == OpenDirection.Entering);
var maleEntering = enterences.Where(x => x.Gender == Gender.Male);
var femaleEntering = enterences.Where(x => x.Gender == Gender.Female);
var exits = doorOpened.Where(o => o.Direction == OpenDirection.Leaving);
var maleExiting = exits.Where(x => x.Gender == Gender.Male);
var femaleExiting = exits.Where(x => x.Gender == Gender.Female);
var malesAcquaintances =
maleEntering
.GroupJoin(femaleEntering,
male => maleExiting.Where(exit => exit.Name == male.Name),
female => femaleExiting.Where(exit => female.Name == exit.Name),
(m, females) => new { Male = m.Name, Females = females });
var amountPerUser =
from acquinteces in malesAcquaintances
from cnt in acquinteces.Females.Scan(0, (acc, curr) => acc + 1)
select new { acquinteces.Male, cnt };
amountPerUser.SubscribeConsole("Amount of meetings per User");
//
// Using Query Syntax GroupJoin clause
//
var malesAcquaintances2 =
from male in maleEntering
join female in femaleEntering on maleExiting.Where(exit => exit.Name == male.Name) equals
femaleExiting.Where(exit => female.Name == exit.Name)
into females
select new { Male = male.Name, Females = females };
var amountPerUser2 =
from acquinteces in malesAcquaintances2
from cnt in acquinteces.Females.Scan(0, (acc, curr) => acc + 1)
select new { acquinteces.Male, cnt };
//amountPerUser2.SubscribeConsole("Amount of meetings per User (query syntax)");
//This is the sequence you see in Figure 9.8
doorOpenedSubject.OnNext(new DoorOpened("Bob", Gender.Male, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("Sara", Gender.Female, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("John", Gender.Male, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("Sara", Gender.Female, OpenDirection.Leaving));
doorOpenedSubject.OnNext(new DoorOpened("Fibi", Gender.Female, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("Bob", Gender.Male, OpenDirection.Leaving));
doorOpenedSubject.OnNext(new DoorOpened("Dan", Gender.Male, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("Fibi", Gender.Female, OpenDirection.Leaving));
doorOpenedSubject.OnNext(new DoorOpened("John", Gender.Male, OpenDirection.Leaving));
doorOpenedSubject.OnNext(new DoorOpened("Dan", Gender.Male, OpenDirection.Leaving));
}
示例9: DynamixelBus
//private readonly Dictionary<byte, DynamixelDevice> _dynamixelDevices = new Dictionary<byte, DynamixelDevice>();
//public ReadOnlyDictionary<byte, DynamixelDevice> Devices
//{
// get { return new ReadOnlyDictionary<byte, DynamixelDevice>(_dynamixelDevices); }
//}
public DynamixelBus(string portName, int baudRate)
{
_port = new DynamixelPort("COM3", 1000000);
_subject = new Subject<IPacket>();
Packets = _subject.AsObservable();
_port.StatusPacketReceived += Add;
Packets.OfType<InstructionPacket>().Subscribe(p => _port.Write(p));
}
示例10: InitializeGlobal
internal static IObservable<Input> InitializeGlobal(IntPtr hwnd, IScheduler scheduler)
{
Mouse.WindowHandle = hwnd;
PreviousMouseState = Mouse.GetState();
PreviousKeyboardState = Keyboard.GetState();
Subject = new Subject<Input>(scheduler);
return Subject.AsObservable();
}
示例11: TimeFliesView
public TimeFliesView(RectangleF rect)
: base(rect)
{
UserInteractionEnabled = true;
_currentTouchPointSubject = new Subject<PointF>();
_currentTouchPointObserver = _currentTouchPointSubject.AsObservable();
var wholeCoverageView = new UIControl(rect) {UserInteractionEnabled = true};
AddSubview(wholeCoverageView); // add one covering the whole view so we get hits
BecomeFirstResponder();
Reactive("Time flies like an arrow");
}
示例12: SearchHints
public SearchHints(IRecentSearchCollection recentSearchCollection, ISchedulerProvider schedulerProvider)
{
//User feedback to guide them whilst typing
var searchText = this.WhenValueChanged(vm => vm.SearchText);
var useRegEx = this.WhenValueChanged(vm => vm.UseRegex);
//if regex then validate
var combined = searchText.CombineLatest(useRegEx, (text, regex) => new SearchRequest(text, regex))
.Throttle(TimeSpan.FromMilliseconds(250))
.Select(searchRequest => searchRequest.BuildMessage())
.Publish();
IsValid = combined.Select(shm => shm.IsValid).DistinctUntilChanged().ForBinding();
Message = combined.Select(shm => shm.Message).DistinctUntilChanged().ForBinding();
var forceRefreshOfError = combined.Select(shm => shm.IsValid)
.DistinctUntilChanged()
.Subscribe(_ =>
{
this.OnPropertyChanged("SearchText");
});
var predictRegex = this.WhenValueChanged(vm => vm.SearchText)
.Select(text => _regexInspector.DoesThisLookLikeRegEx(text))
.Subscribe(likeRegex => UseRegex = likeRegex);
//Handle adding new search
var searchRequested = new Subject<SearchRequest>();
SearchRequested = searchRequested.AsObservable();
AddSearchCommand = new Command(async () =>
{
await Task.Run(() =>
{
recentSearchCollection.Add(new RecentSearch(SearchText));
searchRequested.OnNext(new SearchRequest(SearchText, UseRegex));
SearchText = string.Empty;
UseRegex = false;
});
}, () => IsValid.Value && SearchText.Length > 0);
var dataLoader = recentSearchCollection.Items.Connect()
// .Filter(filter)
.Transform(recentSearch => recentSearch.Text)
.Sort(SortExpressionComparer<string>.Ascending(str => str))
.ObserveOn(schedulerProvider.MainThread)
.Bind(out _hints)
.Subscribe();
_cleanUp = new CompositeDisposable(IsValid, Message, predictRegex, dataLoader, searchRequested.SetAsComplete(), combined.Connect(), forceRefreshOfError);
}
示例13: SearchHints
public SearchHints(IRecentSearchCollection recentSearchCollection, ISchedulerProvider schedulerProvider)
{
//build a predicate when SearchText changes
var filter = this.WhenValueChanged(t => t.SearchText)
.Throttle(TimeSpan.FromMilliseconds(250))
.Select(BuildFilter);
//User feedback to guide them whilst typing
var searchText = this.WhenValueChanged(vm => vm.SearchText);
var useRegEx = this.WhenValueChanged(vm => vm.UseRegex);
//if regex then validate
var combined = searchText.CombineLatest(useRegEx, (text, regex) => new SearchRequest(text, regex))
.Publish();
IsValid = combined.Select(searchRequest => searchRequest.BuildMessage()).ForBinding();
var predictRegex = this.WhenValueChanged(vm => vm.SearchText)
//.Where(text=>!string.IsNullOrEmpty(text))
.Select(text=>_regexInspector.DoesThisLookLikeRegEx(text))
// .DistinctUntilChanged()
.Subscribe(likeRegex=> UseRegex= likeRegex);
//Handle adding new search
var searchRequested = new Subject<SearchRequest>();
SearchRequested = searchRequested.AsObservable();
AddSearchCommand = new Command(() =>
{
recentSearchCollection.Add(new RecentSearch(SearchText));
searchRequested.OnNext(new SearchRequest(SearchText, UseRegex));
SearchText = string.Empty;
UseRegex = false;
}, () => IsValid.Value.IsValid && SearchText.Length>0);
var dataLoader = recentSearchCollection.Items.Connect()
.Filter(filter)
.Transform(recentSearch=> recentSearch.Text)
.Sort(SortExpressionComparer<string>.Ascending(str => str))
.ObserveOn(schedulerProvider.MainThread)
.Bind(out _hints)
.Subscribe();
_cleanUp = new CompositeDisposable( dataLoader, IsValid, predictRegex, Disposable.Create(searchRequested.OnCompleted), combined.Connect());
}
示例14: Join
private static void Join()
{
Demo.DisplayHeader("The Join operator - ...");
Subject<DoorOpened> doorOpenedSubject = new Subject<DoorOpened>();
IObservable<DoorOpened> doorOpened = doorOpenedSubject.AsObservable();
var enterences = doorOpened.Where(o => o.Direction == OpenDirection.Entering);
var maleEntering = enterences.Where(x => x.Gender == Gender.Male);
var femaleEntering = enterences.Where(x => x.Gender == Gender.Female);
var exits = doorOpened.Where(o => o.Direction == OpenDirection.Leaving);
var maleExiting = exits.Where(x => x.Gender == Gender.Male);
var femaleExiting = exits.Where(x => x.Gender == Gender.Female);
//Using Method Chaining apporach
maleEntering
.Join(femaleEntering,
male => maleExiting.Where(exit => exit.Name == male.Name),
female => femaleExiting.Where(exit => female.Name == exit.Name),
(m, f) => new { Male = m.Name, Female = f.Name })
.SubscribeConsole("Together At Room");
//
//Using Query Syntax Join clause
//
var test =
from male in maleEntering
join female in femaleEntering on maleExiting.Where(exit => exit.Name == male.Name) equals
femaleExiting.Where(exit => female.Name == exit.Name)
select new { MName = male.Name, FName = female.Name };
test.SubscribeConsole("Together At Room (query syntax)");
//This is the sequence you see in Figure 9.8
doorOpenedSubject.OnNext(new DoorOpened("Bob", Gender.Male, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("Sara", Gender.Female, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("John", Gender.Male, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("Sara", Gender.Female, OpenDirection.Leaving));
doorOpenedSubject.OnNext(new DoorOpened("Fibi", Gender.Female, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("Bob", Gender.Male, OpenDirection.Leaving));
doorOpenedSubject.OnNext(new DoorOpened("Dan", Gender.Male, OpenDirection.Entering));
doorOpenedSubject.OnNext(new DoorOpened("Fibi", Gender.Female, OpenDirection.Leaving));
doorOpenedSubject.OnNext(new DoorOpened("John", Gender.Male, OpenDirection.Leaving));
doorOpenedSubject.OnNext(new DoorOpened("Dan", Gender.Male, OpenDirection.Leaving));
}
示例15: BindableObject
public BindableObject()
{
changed = new Subject<PropertyChangedData>();
changed.ObserveOn(SchedulerProvider.UIScheduler)
.Subscribe(args =>
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(args.PropertyName));
});
Changed = changed.AsObservable();
changing = new Subject<PropertyChangingData>();
changing.ObserveOn(SchedulerProvider.UIScheduler)
.Subscribe(args =>
{
PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(args.PropertyName));
});
Changing = changing.AsObservable();
}