Rのconnectionをopenしたときとしなかったときの挙動の違い

についてOpenCPUのひとが語ってるのがあるんですが、読めてないです。読めてないんですけど、忘れそうなのでメモ。

Some aspects of connections are a bit confusing: to incrementally read/write data you need to explicitly open() and close() the connection. However, readLines, writeLines, readBin or writeBin will automatically open and close (but not destroy!) an unopened connection.

openしない場合

openしてないコネクションは、readLinesが勝手に開いて閉じてしまいます。なので、何度やってもはじめから読み出します。

library(curl)

con <- curl("https://httpbin.org/get")

cat(readLines(con, n = 2), sep = "\n")
#> {
#>   "args": {}, 
cat(readLines(con, n = 2), sep = "\n")
#> {
#>   "args": {}, 
cat(readLines(con, n = 2), sep = "\n")
#> {
#>   "args": {}, 

openした場合

openした場合はちゃんと続きが読めます。

library(curl)

con <- curl("https://httpbin.org/get")
open(con)

cat(readLines(con, n = 2), sep = "\n")
#> {
#>   "args": {}, 
cat(readLines(con, n = 2), sep = "\n")
#>   "headers": {
#>     "Accept": "*/*", 
cat(readLines(con, n = 2), sep = "\n")
#>     "Accept-Encoding": "gzip, deflate", 
#>     "Host": "httpbin.org", 

どういう時に使うのか

非同期なIOをしたいときとか、でかすぎるデータをちょっとずつストリームとして引っ張ってくるときに使うみたいです。

jsonlitestream_in()/stream_out()あたりを見ればもうちょっと使い方がピンとくる気もしつつ、まったくピンときてないです。

ま、とりあえずメモってことで。