reduxkotlin/redux-kotlin-thunk

Cancel Coroutine Launched Inside a Thunk

Closed this issue · 2 comments

Great library, together with the Redux library it's a great fit for Kotlin multiplatform projects.

The example in the README launches a coroutine inside the thunk. Is there any good way to cancel the coroutine later? The way it is currently it's a fire & forget situation which is not ideal in many cases.

Any updates on this? @ge-org

You could model your thunk builder to take CoroutineScope as an argument. Then you can simply cancel it as needed.

Here's a modified sample

    val store = createStore(::reducer, applymiddleware(createThunkMiddleware()))
    
    ...
    
    fun CoroutineScope.fooThunk(query: String): Thunk<AppState> = { dispatch, getState, extraArg ->
        dispatch(FetchingFooAction)
        launch {
            val result = api.foo(query)
            if (result.isSuccessful()) {
                dispatch(FetchFooSuccess(result.payload)
            } else {
                dispatch(FetchFooFailure(result.message)
            }
        }  
    }
 
    ...
    
    fun bar() {
       val myScope = CoroutineScope(Dispatchers.Default)
       dispatch(myScope.fooThunk("my query"))
       ...
       myScope.cancel()
    }