Finally.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. public 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(
  17. source,
  18. finallyAction,
  19. static async (source, finallyAction, observer) =>
  20. {
  21. var subscription = await source.SubscribeSafeAsync(observer).ConfigureAwait(false);
  22. return AsyncDisposable.Create(async () =>
  23. {
  24. try
  25. {
  26. await subscription.DisposeAsync().ConfigureAwait(false);
  27. }
  28. finally
  29. {
  30. finallyAction();
  31. }
  32. });
  33. });
  34. }
  35. public static IAsyncObservable<TSource> Finally<TSource>(this IAsyncObservable<TSource> source, Func<Task> finallyAction)
  36. {
  37. if (source == null)
  38. throw new ArgumentNullException(nameof(source));
  39. if (finallyAction == null)
  40. throw new ArgumentNullException(nameof(finallyAction));
  41. return Create(
  42. source,
  43. finallyAction,
  44. static async (source, finallyAction, observer) =>
  45. {
  46. var subscription = await source.SubscribeSafeAsync(observer).ConfigureAwait(false);
  47. return AsyncDisposable.Create(async () =>
  48. {
  49. try
  50. {
  51. await subscription.DisposeAsync().ConfigureAwait(false);
  52. }
  53. finally
  54. {
  55. await finallyAction().ConfigureAwait(false);
  56. }
  57. });
  58. });
  59. }
  60. }
  61. }