Fork me on GitHub
#core-async
<
2018-07-16
>
tianshu05:07:40

Is that I should always close all channels after use them? or can just leave them to be collected by GC?

noisesmith17:07:49

it really depends - most of the time one side of the communication or the other should close the channel so the other can stop looping (otherwise the gc can't happen as it's still waiting on the channel)

noisesmith17:07:02

there's some smartness about gc'ing the channel and exiting the go block if there are no other references to the channel, but in my experience it's cleaner to explicitly close (and you should be checking for a closed channel in any code that reads or writes a channel btw.)

tianshu17:07:04

yeah, I just realized that I can exit the loop by close the channel.

noisesmith17:07:13

right - a good habit is to always check the return value of <! and >! and have some way to exit immediately if it returns nil (meaning closed)

tianshu17:07:51

so how can I exit the go block immediately?

tianshu17:07:01

by throw an exception?

noisesmith17:07:11

by having a path that doesn't recur

noisesmith17:07:17

or an if with a branch that exits the block

noisesmith17:07:07

this is in general - sometimes if one channel is closed that means you are done with it and now you read another one - make sure this is relevant to you actual program structure

noisesmith17:07:29

but what you want to avoid is an unchecked >! or <! so that you loop and get nils

tianshu17:07:33

know I found it's good to create channels at the beginning of a procedure, and close them when job is done. instead of create global channels.

tianshu17:07:50

I used to create global channels, and found it really hard to controll

noisesmith17:07:58

also, it's good to write your code such that a channel is passed in

noisesmith17:07:29

(that way your code is more flexible, the client can pass in a channel with a custom buffer and/or transducer to modify the behavior)

tianshu17:07:20

thank you for these advices