本文整理汇总了C#中Subject.Subscribe方法的典型用法代码示例。如果您正苦于以下问题:C# Subject.Subscribe方法的具体用法?C# Subject.Subscribe怎么用?C# Subject.Subscribe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Subject
的用法示例。
在下文中一共展示了Subject.Subscribe方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Subject
///<summary>
///Subject<T> will listen to all publications once subscribed.
///The subscriber will miss all publications made before subscription.
/// </summary>
private static void Subject()
{
var subject = new Subject<string>();
subject.Subscribe( x => Console.WriteLine("Subscritipon 1 : " + x));
subject.OnNext("a");
subject.Subscribe(x => Console.WriteLine("Subscritipon 2 : " + x));
subject.OnNext("b");
subject.OnNext("c");
}
示例2: StopNotifying
public void StopNotifying()
{
var remote = new Subject<bool>();
var tvSubscription = remote.Subscribe(x => Debug.WriteLine("TV on: {0}", x));
var speakerSubscription = remote.Subscribe(x => Debug.WriteLine("Speakers on: {0}", x));
remote.OnNext(true);
speakerSubscription.Dispose();
remote.OnNext(false);
}
示例3: Multicast
// .Publish() = .Multicast(new Subject<T>)
// .PublishLast() = .Multicast(new AsyncSubject<T>)
// .Replay() = .Multicast(new ReplaySubject<T>)
private static void Multicast()
{
var period = TimeSpan.FromSeconds(1);
//var observable = Observable.Interval(period).Publish();
var observable = Observable.Interval(period);
var shared = new Subject<long>();
shared.Subscribe(i => Console.WriteLine("first subscription : {0}", i));
observable.Subscribe(shared); //'Connect' the observable.
Task.Delay(period).Wait();
Task.Delay(period).Wait();
shared.Subscribe(i => Console.WriteLine("second subscription : {0}", i));
Console.ReadKey();
}
示例4: StateHandler
public StateHandler(IDbContextLocator locator, IMessageBusProxy messageBus) {
_locator = locator;
messageBus.Listen<StatusChanged>()
.Subscribe(Handle);
messageBus.Listen<ContentStatusChanged>()
.Subscribe(Handle);
messageBus.Listen<ContentInstalled>()
.Subscribe(Handle);
messageBus.Listen<UninstallActionCompleted>()
.Subscribe(Handle);
messageBus.Listen<GameLaunched>()
.Subscribe(Handle);
messageBus.Listen<GameTerminated>()
.Subscribe(Handle);
messageBus.Listen<RecentItemRemoved>()
.Subscribe(Handle);
messageBus.Listen<ContentUsed>()
.Subscribe(Handle);
messageBus.Listen<ActionNotification>()
.Subscribe(Handle);
messageBus.Listen<ExtensionStateChanged>()
.ConcatTask(Handle)
.Subscribe();
_subject2 = new Subject<ActionTabState>();
_subject = new Subject<StatusModel>();
_subject.Subscribe(Handle);
_subject2.ConcatTask(x => GetActionStateUpdate(x).Raise())
.Subscribe();
}
示例5: EigenUpdateWithoutUpdateURL
public void EigenUpdateWithoutUpdateURL()
{
string dir;
string outDir;
using (Utility.WithTempDirectory(out outDir))
using (IntegrationTestHelper.WithFakeInstallDirectory(out dir)) {
var di = new DirectoryInfo(dir);
var progress = new Subject<int>();
var bundledRelease = ReleaseEntry.GenerateFromFile(di.GetFiles("*.nupkg").First().FullName);
var fixture = new InstallManager(bundledRelease, outDir);
var pkg = new ZipPackage(Path.Combine(dir, "SampleUpdatingApp.1.1.0.0.nupkg"));
var progressValues = new List<int>();
progress.Subscribe(progressValues.Add);
fixture.ExecuteInstall(dir, pkg, progress).Wait();
var filesToLookFor = new[] {
"SampleUpdatingApp\\app-1.1.0.0\\SampleUpdatingApp.exe",
"SampleUpdatingApp\\packages\\RELEASES",
"SampleUpdatingApp\\packages\\SampleUpdatingApp.1.1.0.0.nupkg",
};
filesToLookFor.ForEach(f => Assert.True(File.Exists(Path.Combine(outDir, f)), "Could not find file: " + f));
// Progress should be monotonically increasing
progressValues.Count.ShouldBeGreaterThan(2);
progressValues.Zip(progressValues.Skip(1), (prev, cur) => cur - prev).All(x => x > 0).ShouldBeTrue();
}
}
示例6: Example01
public void Example01()
{
// Hello World, Subscribe to OnNext
// compare Subscribe below to
// subject.PropertyChanged += subject_PropertyChanged
// or
// subject.PropertyChanged += (s, e) => { Console.WriteLine(""); };
var subject = new Subject<string>();
subject.Subscribe(x =>
{
Console.WriteLine(x);
});
subject.OnNext("Hello World");
// OUTPUT
/*
Start
Hello World
End
*/
}
示例7: Run
public static async void Run()
{
var headline = new Subject<string>();
var subscription = headline
//.Where(x => x.Contains("terror"))
.Subscribe(x => Console.WriteLine("{0}: {1}", DateTime.Now, x));
Console.WriteLine("CNN Newscatcher gestartet!");
while (true)
{
var url = string.Format(@"http://rss.cnn.com/rss/edition_europe.rss");
//var data = new WebClient().DownloadString(url);
var data = await new WebClient().DownloadStringTaskAsync(url);
var output = ToUTF8(data);
string[] start = { "<title>" };
List<string> headlines = SubStringCut2(output, start, "</title>");
foreach (var x in headlines)
{
headline.OnNext(x.ToString());
System.Threading.Thread.Sleep(5000);
}
}
}
示例8: Run
public static async void Run()
{
var headline = new Subject <string>();
var subscription = headline
//.Where(x => x.Contains("Anschlag"))
.Subscribe(x => Console.WriteLine("{0}: {1}",DateTime.Now, x));
Console.WriteLine("Standard Newscatcher gestartet!");
while (true)
{
var url = string.Format(@"http://derStandard.at/?page=rss&ressort=Seite1");
//var data = new WebClient().DownloadString(url);
var data = await new WebClient().DownloadStringTaskAsync(url);
var output = ToUTF8(data);
string[] start = { "<title>" };
List<string> headlines = SubStringCut2(output,start,"</title>");
foreach (var x in headlines)
{
headline.OnNext(x.ToString());
System.Threading.Thread.Sleep(3000);
}
}
}
示例9: ViewModel
protected ViewModel()
{
// Need dependency injection
InStreamAsync = new Subject<string>();
OutStreamAsync = new Subject<string>();
ExceptionsAsync = new Subject<Exception>();
OutStreamAsync.Subscribe(SendAsync);
// this does not match the signiture.... may need to create some kind of proxy or fisade...
//InStreamAsync.Subscribe(OnReceivedAsync);
ExceptionsAsync.Subscribe(HandleException); // need to implement
ProcessIntervalMilSec = 1000;
_workers = this.GetType()
.GetMethodsWithAttribute<AsyncWorkerAttribute>()
.ToObservable();
Observable.FromEventPattern<PropertyChangedEventArgs>(this, "PropertyChanged")
.Subscribe(x =>
{
string name = x.EventArgs.PropertyName;
string value = this.GetType().GetProperty(name).GetValue(this, null).ToString();
OutStreamAsync.OnNext(value);
});
}
示例10: DoALongRunningOperation
public void DoALongRunningOperation(string id)
{
var subject = new Subject<string>();
subject.ToClientside().Observable<RxHub>(id);
var debugObserver = subject.Subscribe(
s => Debug.Print("OnNext: \"{0}\"", s),
ex => Debug.Print("OnError: \"{0}\"", ex.Message),
() => Debug.WriteLine("OnCompleted: we are done!")
);
Task.Run(() =>
{
Debug.WriteLine("Publishing \"just started\"...");
subject.OnNext("just started");
Thread.Sleep(1000);
Debug.WriteLine("Publishing \"One second passed, I'm still running\"...");
subject.OnNext("One second passed, I'm still running");
Thread.Sleep(5000);
Debug.WriteLine("Publishing \"Another five seconds passed, I'm still running\"...");
subject.OnNext("Another five seconds passed, I'm still running");
Thread.Sleep(5000);
Debug.WriteLine("Publishing \"Almost done\"...");
subject.OnNext("Almost done");
Debug.WriteLine("Completing...");
subject.OnCompleted();
Debug.WriteLine("Completed.");
});
}
示例11: Run
public static void Run(IItem[] items)
{
var subjects = new Subject<IItem>();
subjects.Subscribe(x => Console.WriteLine($"Neuer Ball: {x.Description}"));
subjects.Subscribe(x => Console.WriteLine($"Preis: {x.Price.Amount} {x.Price.Unit}"));
var t = new Thread(() =>
{
foreach (var x in items)
{
Thread.Sleep(250);
subjects.OnNext(x);
}
});
t.Start();
}
示例12: Run
/*
## Mutable elements cannot be protected
While the AsObservable method can encapsulate your sequence, you should still be aware that it gives no protection against mutable elements.
Side effects should be avoided where possible. Any combination of concurrency with shared state will commonly demand the need for complex locking, deep understanding of CPU architectures and how they work with the locking and optimization features of the language you use.
The simple and preferred approach is
- to avoid shared state,
- favor immutable data types and utilize query composition and transformation.
Hiding side effects into Where or Select clauses can make for very confusing code.
If a side effect is required, then the Do method expresses intent that you are creating a side effect by being explicit.
*/
public static void Run()
{
var source = new Subject<Account>();
//Evil code. It modifies the Account object.
source.Subscribe(account => account.Name = "Garbage");
//unassuming well behaved code
source.Subscribe(
account=>Console.WriteLine("{0} {1}", account.Id, account.Name),
()=>Console.WriteLine("completed"));
source.OnNext(new Account {Id = 1, Name = "Microsoft"});
source.OnNext(new Account {Id = 2, Name = "Google"});
source.OnNext(new Account {Id = 3, Name = "IBM"});
source.OnCompleted();
}
示例13: EventStreamsHaveMultipleEvents
public void EventStreamsHaveMultipleEvents()
{
int eventStreamResult = 0;
var events = new Subject<int>();
events.Subscribe(i => eventStreamResult += i);
events.OnNext(10);
events.OnNext(7);
Assert.AreEqual(____, eventStreamResult);
}
示例14: Run
public void Run()
{
ConsoleUtility.PrintSuccess(string.Format("Rx unsubcribe using dispose"));
var values = new Subject<int>();
var firstSubscription = values.Subscribe(value =>
Console.WriteLine("1st subscription received {0}", value));
var secondSubscription = values.Subscribe(value =>
Console.WriteLine("2nd subscription received {0}", value));
values.OnNext(0);
values.OnNext(1);
values.OnNext(2);
values.OnNext(3);
firstSubscription.Dispose();
Console.WriteLine("Disposed of 1st subscription");
values.OnNext(4);
values.OnNext(5);
}
示例15: Main
protected override void Main()
{
TraceLine(Instructions.PressAnyKeyToCancel);
#if WINDOWS_PHONE && !WINDOWS_PHONE_70
IObservable<string> monitor = ObservableNetworkChange.NetworkAvailability
.Select(e => e.NetworkInterface.InterfaceName + " -> " + e.NotificationType.ToString());
#else
IObservable<bool> monitor = ObservableNetworkChange.NetworkAvailability;
#endif
#if SILVERLIGHT
monitor = monitor.SubscribeOn(new DispatcherScheduler(Dispatcher));
#endif
#if WINDOWS_PHONE && !WINDOWS_PHONE_70
var addresses = new Subject<NetworkInterfaceList>();
Dispatcher.BeginInvoke(() => ObservableNetworkChange.NetworkAddress.Subscribe(addresses));
using (addresses)
using (addresses.Subscribe(
ConsoleOutputOnNext<NetworkInterfaceList>(
Text.NetworkAddresses,
a => a.Aggregate(string.Empty, (acc, addr) => acc + Environment.NewLine + addr.InterfaceName)),
ConsoleOutputOnCompleted()))
#elif !SILVERLIGHT
IObservable<NetworkInterface[]> addresses = ObservableNetworkChange.NetworkAddress;
using (addresses.Subscribe(
ConsoleOutputOnNext<NetworkInterface[]>(
Text.NetworkAddresses,
a => a.Aggregate(string.Empty, (acc, addr) => acc + Environment.NewLine + addr.Name)),
ConsoleOutputOnCompleted()))
#endif
using (monitor.Subscribe(ConsoleOutput(Text.NetworkAvailability)))
{
TraceLine();
TraceDescription(Instructions.DisableYourNetwork);
WaitForKey();
}
}