Odonno / ReduxSimple

Simple Stupid Redux Store using Reactive Extensions
http://www.nuget.org/packages/ReduxSimple/
MIT License
143 stars 19 forks source link

How would I await an effect? #65

Closed steffos closed 4 years ago

steffos commented 4 years ago

I'm looking for something like:

await Store.DispatchAsync(new LoadMyEntitiesAction());
DoSomethingWhenTheAboveLineIsFinished();

I can't do: await Store.Dispatch(new LoadMyEntitiesAction()) since Dispatch is returning void.

Maybe there's a concept I'm missing here?

Odonno commented 4 years ago

Hi @steffos

Can you add more details about your use case?

To give you some info, a dispatcher/action is synchronous so you cannot put await before. If you want to use asynchronous code, you can either subscribe to the action dispatched or use the new Effect pattern that is now in the v3 of ReduxSimple.

ObserveAction

Store.ObserveAction<LoadMyEntitiesAction>().Subscribe(_ =>
{
    // TODO
});

Effect

public static Effect<RootState> GetTodos = CreateEffect<RootState>(
    () => Store.ObserveAction<GetTodosAction>()
        .Select(_ => _todoApi.GetTodos())
        .Switch()
        .Select(todos => 
        {
            return new GetTodosFulfilledAction
            {
                Todos = todos.ToImmutableList()
            };
        })
        .Catch(e => 
        {
            return Observable.Return(
                new GetTodosFailedAction
                {
                    StatusCode = e.StatusCode,
                    Reason = e.Reason
                }
            );
        }),
    true // indicates if the ouput of the effect should be dispatched to the store
);

If you want more explanation, you can also check the readme file which contains some definitions and examples.

steffos commented 4 years ago

Ah, got it! Thanks for an excellent library :)

Odonno commented 4 years ago

Thank you for saying that!