News for hackers. Stuff that matters.
Re:Ask HN: What are some cool but obscure data structures yo... by Ryuuke5 on Friday July 22, 2022 @05:46AM (#32190264)
Sure it's possible, we need to await for the Task if it already exists on the dictionary, for example we could imagine writing something like this inside an actor to make it threadSafe.

    private var tasksDictionary: Dictionary<String, Task<Data, Error>>

    func getData(at urlString: String) async throws -> Data {
        if let currentTask = tasksDictionary[urlString] {
            return await currentTask.value
        }
        let currentTask = Task { 
           return try await URLSession.shared.data(from: URL(string:urlString)!) 
        }
        tasksDictionary[urlString] = currentTask
        let result = await currentTask.value
        tasksDictionary[urlString] = nil
        return result
    }
Re:Ask HN: What are some cool but obscure data structures yo... by ninkendo on Friday July 22, 2022 @01:55PM (#32195024)
Hmm, why set `taskDictionary[urlString] = nil` at the bottom there? If the whole point is to cache the result, isn't the point to leave the value there for other requests to pick it up?
Re:Ask HN: What are some cool but obscure data structures yo... by Ryuuke5 on Friday July 22, 2022 @02:36PM (#32195567)
Yup, nice catch, no need to reset it to nil if you wanna keep it in memory indefinitely.

I guess making it nil can be also used if you don't wanna make the same request when there is one already in flight, in case you have a 403 error and need to request a refresh token, you don't wanna make two simultaneous requests, but you also don't wanna catch it indefinitely either.

Re:Ask HN: What are some cool but obscure data structures yo... by afro88 on Friday July 22, 2022 @06:29AM (#32190468)
Great! So much nicer than the Combine (or Rx) version.