net-daemon / netdaemon

An application daemon for Home Assistant written in .NET
MIT License
226 stars 64 forks source link

DelayUntilStateChange with TimeOut #198

Closed ngelotte closed 3 years ago

ngelotte commented 4 years ago

The problem

Often in a automation I need to wait for the state to change before taking the next action. However, I don't want to wait indefinitely because that probably means something has failed or is not working as expected. So I need to be able to put in a timeout as well so that it will continue on after either the state changes or the timeout occurs.

The proposed solution

Extend DelayUntilStateChange to have the option of passing in a TimeSpan for the desired TimeOut.

The alternatives

This can be done manually a few ways currently. Either by using the TimeOut on an observable or By Using DelayUntilStateChange along with a task.delay and whenAny. It would just be nice to have it built in.

helto4real commented 3 years ago

@ngelotte can you please write example here and I can add it to API. using the alternative as described please.

ngelotte commented 3 years ago

I wrote this extension which I have been using extensively in my code. It has worked well but I know to check for the TimeOut state. I could not think of a better way to do it but I am happy to discuss it.

` public static IObservable<(EntityState Old, EntityState New)> FirstOrTimeout(this IObservable<(EntityState Old, EntityState New)> observable, TimeSpan timeout) {

        return observable.Timeout(timeout, Observable.Return((new NetDaemon.Common.EntityState() { State = "TimeOut" }, new NetDaemon.Common.EntityState() { State = "TimeOut" }))).Take(1);

    }`