How to determine when a core.async channel is closed from the writer's side?
Asked Answered
O

3

7

I have a process that is basically part of a long polling implementation. In a nutshell, the client makes a request to the server, which then creates a channel and returns it to that client. The channel will contain the information that client asked for. Because this is intended to be used for long polling, the information that the client has requested can change. If the information changes, the server will write the update to the channel, and in theory, the client can grab the update and reflect that.

The problem I am facing is that there is a chance that I end up with tons of channels, which can cause unnecessary processing when an update occurs. I could potentially be updating channels where the client no longer cares.

My solution was that once the client stops caring about the information, it closes the channel, which will somehow notify the server, and prevent the server from doing additional processing and updates.

How can the server know if a channel is closed? In this scenario, the server is essentially a writer and does not read anything from the channel. Also, all the writing methods are wrapped in a go block, so it always returns a channel (I don't see any nils). Is there a way to do this, or is my approach completely off?

Thanks

Organic answered 23/7, 2014 at 14:17 Comment(0)
G
7

As of earlier this year, there's a new feature called "putret" this change makes it so all put functions return false if the put fails due to the channel being closed. This allows for idioms like this:

(when (>! c val)
  (recur (next itms)))
Gaven answered 9/9, 2014 at 20:10 Comment(0)
K
4

You can use clojure.core.async.impl.protocols/closed?. As many thing in clojure core.async is 99% finished:)

IMO "producer side closures only" view is rather misleading. Producer could be dead or unresponsive or you might want to re-start your system, or parts of it, without recurring various alts! obfuscating patterns with "stopping channels" etc.

Koa answered 1/7, 2017 at 21:59 Comment(0)
S
3

See the discussion at the link below, and note the advice "You're only supposed to close a channel from the producer side."

https://groups.google.com/forum/#!topic/clojure/_KzEoq0XcHQ

Schwing answered 14/8, 2014 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.