3

I need to automatically back up my files from external drivers (such as usb keys) When the driver is plugged in. to know when a new usb or hard drive is inserted I used an observable, the problem is that the only way I know about getting connected drivers is by using the function:

DriveInfo.GetDrives();

returning the list containing each linked driver: and I implement this function to know when a new mass memory is connected:

       public static IObservable<DriveInfo> ObserveNewDrivers() =>
        Observable.Interval(TimeSpan.FromSeconds(5))
            .Select(_ => DriveInfo
                .GetDrives())
            .DistinctUntilChanged()
            .Buffer(2)
            .SelectMany(buff => buff.Aggregate(
                (a, b) => b.Except(a).ToArray()));

it does not work because I only compare the pair of two-to-two drivers (using the "Except" function) numerical example: 1,2; 3.4; 5.6;. In this way if I re-insert the same driver I will double backup it twice because i don't compare 3th driver with the first (for example).

I think the behavior I need is the pairwise operator in rxjs but not in .net ie: 1.2; 2.3; 3.4; 4.5; 5.6; etc

ps. sorry if I was not too clear and for my poor english :^)

thanks for any answers

  • Your description doesn't make sense when I try to compare it against the code. Can you describe what you're trying to do in terms of your business requirement? – Enigmativity Sep 10 '17 at 09:23
  • What I need is an observable that notify me when new driver is plugged in the computer. – Luca Gorzog Sep 10 '17 at 11:27
  • You probably want to use Scan after the .DistinctUntilChanged so you can keep the previous results of DriveInfo.GetDrives around and then compare with the latest to see what is new, old and remained the same. – user630190 Sep 11 '17 at 07:58
  • I found another way : Observable.Interval(TimeSpan.FromSeconds(5)) .SelectMany(_ => DriveInfo.GetDrives()) .Distinct(); Much simpler than I thought, but I am still curious about how to implement pairwise operator – Luca Gorzog Sep 11 '17 at 13:20

1 Answers1

3

Buffer in .NET has a constructor with 2 arguments which allows you to do an 'overlapping' buffer.

If my understanding of the problem you face is correct, you would want to use:

.Buffer(2, 1)

which means that two values will be emitted on every 1 new value. More info here:

http://www.introtorx.com/Content/v1.0.10621.0/13_TimeShiftedSequences.html#Buffer

See section 'overlapping buffers by count'.

aleksk
  • 661
  • 7
  • 15