gpt4 book ai didi

f# - 如何在 Prop 更改时取消 Cmd.OfAsync?

转载 作者:行者123 更新时间:2023-12-04 13:30:17 27 4
gpt4 key购买 nike

假设我有一个受控的 Elmish 形式:

type Model = 
{
Query : string
IsLoading : bool
Result : Result<QueryResults, string> option
}

type Message =
| UpdateQuery of string
| ReceivedResults of Result<QueryResults, string>

let update message model =
match message with
| UpdateQuery query ->
let nextModel =
{
model with
Query = query
IsLoading = true
}

let cmd =
Cmd.OfAsync.result (async {
let! results = Api.tryFetchQueryResults query

return ReceivedResults results
})

nextModel, cmd
| ReceivedResults results ->
{
model with
IsLoading = false
Results = Some results
}, Cmd.none
每次 model.Query发生变化,它会发送一个 async要求。但是,如果已经有正在进行的请求,我希望取消该请求并替换为新的请求。
在 Elmish 中这样做的好方法是什么?

最佳答案

没有任何内置支持取消底层 XMLHttpRequest .
但是,我们可以构建一些支持类似取消功能的小型机器:
首先,增加您的 Model有关当前待处理查询的信息,以及您的 Message带有指向该查询的链接(一个简单的 Guid 即可)

open System

type Model =
{
Query : string
IsLoading : bool
Result : Result<QueryResults, string> option
PendingQuery: Guid option
}

type Message =
| UpdateQuery of string
| ReceivedResults of Guid * Result<QueryResults, string>
接下来,在您的 update 中提供这些数据。功能
  | UpdateQuery query ->

let correlationId = Guid.NewGuid()

let nextModel =
{
model with
Query = query
IsLoading = true
PendingQuery = Some correlationId
}

let cmd =
Cmd.OfAsync.result (async {
let! results = Api.tryFetchQueryResults query

return ReceivedResults (correlationId, results)
})

nextModel, cmd
最后,在从服务器接收数据时检查挂起的查询并忽略与链接不匹配的内容
  | ReceivedResults (correlationId, results) ->
match model.PendingQuery with
| Some id when id = correlationId ->
{
model with
IsLoading = false
PendingQuery = None
Result = Some results
}, Cmd.none
| _ -> model, Cmd.none

关于f# - 如何在 Prop 更改时取消 Cmd.OfAsync?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65457001/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com