Finally.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Reactive.Disposables;
  5. using System.Threading.Tasks;
  6. namespace System.Reactive.Linq
  7. {
  8. partial class AsyncObservable
  9. {
  10. public static IAsyncObservable<TSource> Finally<TSource>(this IAsyncObservable<TSource> source, Action finallyAction)
  11. {
  12. if (source == null)
  13. throw new ArgumentNullException(nameof(source));
  14. if (finallyAction == null)
  15. throw new ArgumentNullException(nameof(finallyAction));
  16. return Create<TSource>(async observer =>
  17. {
  18. var subscription = await source.SubscribeSafeAsync(observer).ConfigureAwait(false);
  19. return AsyncDisposable.Create(async () =>
  20. {
  21. try
  22. {
  23. await subscription.DisposeAsync().ConfigureAwait(false);
  24. }
  25. finally
  26. {
  27. finallyAction();
  28. }
  29. });
  30. });
  31. }
  32. public static IAsyncObservable<TSource> Finally<TSource>(this IAsyncObservable<TSource> source, Func<Task> finallyAction)
  33. {
  34. if (source == null)
  35. throw new ArgumentNullException(nameof(source));
  36. if (finallyAction == null)
  37. throw new ArgumentNullException(nameof(finallyAction));
  38. return Create<TSource>(async observer =>
  39. {
  40. var subscription = await source.SubscribeSafeAsync(observer).ConfigureAwait(false);
  41. return AsyncDisposable.Create(async () =>
  42. {
  43. try
  44. {
  45. await subscription.DisposeAsync().ConfigureAwait(false);
  46. }
  47. finally
  48. {
  49. await finallyAction().ConfigureAwait(false);
  50. }
  51. });
  52. });
  53. }
  54. }
  55. }