|
| 1 | +open System |
| 2 | +open System.IO |
| 3 | +open FSharp.Data.Adaptive |
| 4 | +open System.Threading |
| 5 | + |
| 6 | +// This example uses AdaptiveDirectory and AdaptiveFile to read all lines |
| 7 | +// from all files in a directory maintaining a single adaptive list of lines. |
| 8 | + |
| 9 | +[<EntryPoint>] |
| 10 | +let main _argv = |
| 11 | + |
| 12 | + // create a temporary directory |
| 13 | + let dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid() |> string) |
| 14 | + Directory.CreateDirectory dir |> ignore |
| 15 | + |
| 16 | + // get the lines of all files (sorted by name) concatenated in one alist. |
| 17 | + let content = |
| 18 | + AdaptiveDirectory.GetFiles(dir, true) |
| 19 | + |> ASet.sortBy (fun info -> info.Name) |
| 20 | + |> AList.collect (fun info -> |
| 21 | + AdaptiveFile.ReadAllLinesAList info.FullName |
| 22 | + ) |
| 23 | + |
| 24 | + // for demonstration purposes we want to wait until the |
| 25 | + // callback gets executed after each change, therefore |
| 26 | + // we use a Semaphore here. |
| 27 | + let callbackSem = new SemaphoreSlim(0) |
| 28 | + |
| 29 | + // subscribe to changes and pretty-print the changes. |
| 30 | + let subscription = |
| 31 | + content.AddCallback (fun oldState delta -> |
| 32 | + // print the change |
| 33 | + Pretty.print 1 (IndexList.toListIndexed oldState) (IndexListDelta.toList delta) |
| 34 | + printfn "" |
| 35 | + |
| 36 | + // tell the main-thread we're done printing |
| 37 | + callbackSem.Release() |> ignore |
| 38 | + ) |
| 39 | + |
| 40 | + // some temporary files |
| 41 | + let a = Path.Combine(dir, "a.txt") |
| 42 | + let b = Path.Combine(dir, "b.txt") |
| 43 | + let c = Path.Combine(dir, "c.txt") |
| 44 | + let d = Path.Combine(dir, "d.txt") |
| 45 | + |
| 46 | + // perform some changes and wait for our print |
| 47 | + printfn "write a.txt" |
| 48 | + File.WriteAllText(a, "This is file a") |
| 49 | + callbackSem.Wait() |
| 50 | + |
| 51 | + printfn "write c.txt" |
| 52 | + File.WriteAllText(c, "File c has\r\ntwo lines") |
| 53 | + callbackSem.Wait() |
| 54 | + |
| 55 | + printfn "write b.txt" |
| 56 | + File.WriteAllText(b, "b also exists now!") |
| 57 | + callbackSem.Wait() |
| 58 | + |
| 59 | + printfn "update b.txt" |
| 60 | + File.WriteAllText(b, "b has a new line!\r\nb also exists now!\r\nand another one") |
| 61 | + callbackSem.Wait() |
| 62 | + |
| 63 | + printfn "delete a.txt" |
| 64 | + File.Delete a |
| 65 | + callbackSem.Wait() |
| 66 | + |
| 67 | + printfn "write a.txt" |
| 68 | + File.WriteAllText(a, "THIS\r\nIS FILE A") |
| 69 | + callbackSem.Wait() |
| 70 | + |
| 71 | + printfn "b.txt -> d.txt" |
| 72 | + File.Move(b, d) |
| 73 | + callbackSem.Wait() |
| 74 | + |
| 75 | + |
| 76 | + // dispose our subscription and delete the temp-directory |
| 77 | + subscription.Dispose() |
| 78 | + Directory.Delete(dir, true) |
| 79 | + |
| 80 | + |
| 81 | + 0 |
0 commit comments