英文:
Is there a visual in debug I can see the difference of using Dispose method on observable
问题
Given:
.Net 6控制台应用程序
Visual Studio 2022
在调试时是否有可视化方式来查看释放可观察对象与忘记释放它之间的区别?
https://dotnetfiddle.net/bNFwoQ
using System;
using System.Reactive.Linq;
namespace ObserverPatternPractice
{
class Program
{
static void Main(string[] args)
{
// 步骤 1 创建可观察对象。
var observable = Observable.Range(5, 8);
// 步骤 2 订阅可观察对象。
var subscription = observable.Subscribe(new Observer());
// 步骤 3 为 OnNext 事件提供实现。
// 步骤 4 当不再需要监听时,释放订阅。
subscription.Dispose();
}
}
class Observer : IObserver<int>
{
public void OnCompleted()
{
Console.WriteLine("流已完成信号");
}
public void OnError(Exception error)
{
Console.WriteLine("错误信号事件");
}
public void OnNext(int value)
{
Console.WriteLine($"OnNext 值为 {value}");
}
}
}
英文:
Given:
.Net 6 console application
Visual Studio 2022
Is there a visual when debugging that I can see the difference of disposing the observable vs forgetting to dispose of it?
https://dotnetfiddle.net/bNFwoQ
using System;
using System.Reactive.Linq;
namespace ObserverPatternPractice
{
class Program
{
static void Main(string[] args)
{
//Step 1 Create the observable.
var observable = Observable.Range(5, 8);
//Step 2 Subscribe to the observable.
var subscription = observable.Subscribe(new Observer());
//Step 3 Provide implementation for OnNext even.
//Step 4 Dispose of the subscription when you
//do not want to listen anymore.
subscription.Dispose();
}
}
class Observer : IObserver<int>
{
public void OnCompleted()
{
Console.WriteLine("Stream completed signal");
}
public void OnError(Exception error)
{
Console.WriteLine("Error signal event");
}
public void OnNext(int value)
{
Console.WriteLine($"OnNext value is {value}");
}
}
}
答案1
得分: 1
尝试使用这个扩展方法:
public static IObservable<T> OnUnsubscribe<T>(this IObservable<T> source, Action unsubscribe) =>
Observable
.Create<T>(o =>
new CompositeDisposable(
source.Subscribe(o),
Disposable.Create(unsubscribe)));
然后将你的可观察对象更改为:
var observable = Observable.Range(5, 8).OnUnsubscribe(() => Console.WriteLine("Disposed"));
然后你的代码将产生:
OnNext value is 5
OnNext value is 6
OnNext value is 7
OnNext value is 8
OnNext value is 9
OnNext value is 10
OnNext value is 11
OnNext value is 12
Stream completed signal
Disposed
英文:
Try using this extension method:
public static IObservable<T> OnUnsubscribe<T>(this IObservable<T> source, Action unsubscribe) =>
Observable
.Create<T>(o =>
new CompositeDisposable(
source.Subscribe(o),
Disposable.Create(unsubscribe)));
And change your observable to this:
var observable = Observable.Range(5, 8).OnUnsubscribe(() => Console.WriteLine("Disposed"));
Then your code produces:
OnNext value is 5
OnNext value is 6
OnNext value is 7
OnNext value is 8
OnNext value is 9
OnNext value is 10
OnNext value is 11
OnNext value is 12
Stream completed signal
Disposed
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论