# LibTmux.FSharp.Control.foldWhile

- **Module:** LibTmux.FSharp
- **Package:** LibTmux.FSharp
- **Language:** F#
- **Kind:** function
- **Source:** https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/src/LibTmux.FSharp/Control.fsi#L99
- **Page:** https://libtmux.org/en/fsharp/latest/reference/libtmux-fsharp-control-foldwhile/

```
val foldWhile:
        cancellationToken: CancellationToken ->
        folder: ('State -> 'T -> Task<StreamStep<'State>>) ->
        initial: 'State ->
        source: IAsyncEnumerable<'T> ->
            Task<'State>
```

Folds items until the stream ends or the folder returns Stop.

The helper disposes its enumerator but leaves the control client open.

## Examples

Attach one control client, then follow two panes' output as each event names its pane. Each pane's end arrives as TmuxPaneGoneEvent in the order the panes were given. Use Linux or macOS with Git, tmux 3.2a or newer, .NET SDK 10.0.303, and the .NET 8 and 10 runtimes. In an empty directory, fetch the documented library revision:

```console
$ git clone https://github.com/libtmux/libtmux-dotnet.git libtmux-source && \
  git -C libtmux-source checkout --detach cf34b255c896d19a97e7d7fabea58609c916012d
```

Save this complete consumer setup as global.json:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/global.json).

```json
{
  "sdk": {
    "version": "10.0.303",
    "rollForward": "disable",
    "allowPrerelease": false
  },
  "test": {
    "runner": "Microsoft.Testing.Platform"
  }
}
```

Save this complete consumer setup as NuGet.config:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/api/NuGet.config).

```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear />
    <add key="libtmux-source" value="libtmux-source/artifacts/api-example-packages" />
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
  <packageSourceMapping>
    <clear />
    <packageSource key="libtmux-source">
      <package pattern="LibTmux" />
      <package pattern="LibTmux.*" />
    </packageSource>
    <packageSource key="nuget.org">
      <package pattern="*" />
    </packageSource>
  </packageSourceMapping>
</configuration>
```

Save this complete consumer setup as Example.fsproj:

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/api/fsharp/Example.fsproj).

```xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>net8.0;net10.0</TargetFrameworks>
    <LangVersion>10.0</LangVersion>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <DisableImplicitFSharpCoreReference>true</DisableImplicitFSharpCoreReference>
    <DisableImplicitLibraryPacksFolder>true</DisableImplicitLibraryPacksFolder>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="Program.fs" />
    <PackageReference Include="FSharp.Core" Version="[10.1.303]" />
    <PackageReference Include="LibTmux.FSharp" Version="[0.0.0-alpha.20]" />
  </ItemGroup>
</Project>
```

Save this complete program as Program.fs. It creates a private server with LibTmux.Server.CreateOwnedAsync; use! disposes owned scopes after success, cancellation or failure. The F# facade has no separate server constructor.

[Source example](https://github.com/libtmux/libtmux-dotnet/blob/cf34b255c896d19a97e7d7fabea58609c916012d/examples/LibTmux.FSharp.Examples/Programs/WatchPanes.fs).

```fsharp
// fsharp-snippet: WatchPanes
open System
open System.Threading
open LibTmux
open LibTmux.FSharp

let runAsync () =
    task {
        use deadline = new CancellationTokenSource(TimeSpan.FromSeconds 20.)
        let token = deadline.Token

        let options =
            ServerConnectionOptions(
                SocketName = "fsharp-watch-panes-" + Guid.NewGuid().ToString("N"),
                ConfigurationFile = "/dev/null"
            )

        use! owned = options |> Server.createOwned token

        let! session =
            owned.Value
            |> Server.newSession token (SessionSpec.running "work" "exec sleep 60")

        // The client buffers everything from the moment it attaches, so the
        // panes it should see can start afterwards.
        use! client = session |> Control.enterSession token
        let! first = session |> Session.panes |> Query.list token

        let start command =
            first[0] |> Pane.split token (SplitPaneRequest(Command = command))

        let! build = start "printf 'build: ok\\n'; exec sleep 60"
        let! test = start "printf 'test: ok\\n'; exec sleep 60"

        // One client, both panes: each output event names its pane.
        let! printed =
            client
            |> Control.watchPanes [ build; test ]
            |> Control.foldWhile
                token
                (fun (printed: Map<string, string>) event ->
                    task {
                        match event with
                        | PaneWatch.Output output ->
                            let pane = output.PaneId.ToString()
                            let sofar = printed |> Map.tryFind pane |> Option.defaultValue ""
                            let printed = printed |> Map.add pane (sofar + output.Data)

                            if printed.Count = 2 && printed |> Map.forall (fun _ text -> text.Contains '\n') then
                                return StreamStep.Stop printed
                            else
                                return StreamStep.Continue printed
                        | _ -> return StreamStep.Continue printed
                    })
                Map.empty

        // Each pane's end arrives as PaneWatch.Gone, and the stream ends
        // once both are gone.
        do! build |> Pane.kill token
        do! test |> Pane.kill token

        let! ended =
            client
            |> Control.watchPanes [ build; test ]
            |> Control.foldWhile
                token
                (fun ended event ->
                    task {
                        match event with
                        | PaneWatch.Gone pane -> return StreamStep.Continue(ended @ [ pane ])
                        | _ -> return StreamStep.Continue ended
                    })
                []

        for pane in [ build; test ] do
            printfn "%s" (printed[pane.Id.ToString()].Trim())

        printfn "ended in order given: %b" (ended = [ build.Id; test.Id ])
    }

runAsync().GetAwaiter().GetResult()
// endfsharp-snippet
```

Build the exact source packages and the saved consumer, then run both supported frameworks. The local package feed prevents an unrelated published package from satisfying the restore. Each program checks its result and exits unsuccessfully after an unhandled error:

```console
$ export NUGET_PACKAGES="$PWD/packages" && \
  dotnet restore libtmux-source/src/LibTmux.FSharp/LibTmux.FSharp.fsproj --locked-mode && \
  dotnet pack libtmux-source/src/LibTmux/LibTmux.csproj \
    --configuration Release --no-restore -p:ContinuousIntegrationBuild=true \
    --output "$PWD/libtmux-source/artifacts/api-example-packages" && \
  dotnet pack libtmux-source/src/LibTmux.FSharp/LibTmux.FSharp.fsproj \
    --configuration Release --no-restore -p:ContinuousIntegrationBuild=true \
    --output "$PWD/libtmux-source/artifacts/api-example-packages" && \
  dotnet restore Example.fsproj --configfile NuGet.config && \
  dotnet build Example.fsproj --configuration Release --no-restore --warnaserror && \
  export LIBTMUX_TMUX="$(command -v tmux)" && \
  export TMUX_TMPDIR=/tmp/libtmux-dotnet-dev && \
  mkdir -p "$TMUX_TMPDIR" && \
  unset TMUX TMUX_PANE && \
  dotnet bin/Release/net8.0/Example.dll && \
  dotnet bin/Release/net10.0/Example.dll
```

Expected program output from each framework:

```text
build: ok
test: ok
ended in order given: true
```

## Parameters

- `cancellationToken` (`CancellationToken`)
- `folder` (`('State -> 'T -> Task<StreamStep<'State>>)`)
- `initial` (`'State`)
- `source` (`IAsyncEnumerable<'T>`)
