Pontus Magnusson
Pontus Magnusson

Reputation: 651

Merge two events, detect which is raised

I have two buttons, and I want to merge their click events, and then wait for either of them to be clicked (using async), and then depending on which button got pressed, I want to perform different actions.

I have been trying to use Async.AwaitObservable with Observable.merge but I can't get it to work (does it even exist?) and I have been trying to use Observable.map to assign returnvalues to the event, but I cant get anything to work.

I want to use a match expression to perform different actions based on what button I click.

Storytime:
This is to prevent my program from having mutables.
My program is a drawing program using windows forms and f#.
It should be able to draw two diffrent shapes and I dont want to keep track of which "tool" I'm using by using mutables, so instead I want to await the event and determine from there.

Upvotes: 1

Views: 105

Answers (1)

kaefer
kaefer

Reputation: 5741

Since there's no Async.AwaitObservable method (at least on my system), using Async.AwaitEvent and the equivalent functions of the Event module instead of Observable should work.

type WhichButton = B0Clicked | B1Clicked

let clicks =
    (   b0.Click |> Event.map (fun _ -> B0Clicked) ,
        b1.Click |> Event.map (fun _ -> B1Clicked) )
    ||> Event.merge 

let waitForClicks() = async{
    while true do
        let! clicked = Async.AwaitEvent clicks
        match clicked with
        | B0Clicked -> printfn "Button 0"
        | B1Clicked -> printfn "Button 1" }

Upvotes: 1

Related Questions