についてOpenCPUのひとが語ってるのがあるんですが、読めてないです。読めてないんですけど、忘れそうなのでメモ。
Some aspects of connections are a bit confusing: to incrementally read/write data you need to explicitly
open()andclose()the connection. However,readLines,writeLines,readBinorwriteBinwill 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をしたいときとか、でかすぎるデータをちょっとずつストリームとして引っ張ってくるときに使うみたいです。
jsonliteのstream_in()/stream_out()あたりを見ればもうちょっと使い方がピンとくる気もしつつ、まったくピンときてないです。
ま、とりあえずメモってことで。