つまらないシステム(2) - Scala 書きやすすぎるFutureの罠

D5c7b3659d50696454ca0e6dceaf1f53?s=47 mashijp
November 13, 2015

つまらないシステム(2) - Scala 書きやすすぎるFutureの罠

Scalaで詰まらないシステムを作るために覚えていてほしいこと。

D5c7b3659d50696454ca0e6dceaf1f53?s=128

mashijp

November 13, 2015
Tweet

Transcript

  1. ͭ·Βͳ͍γεςϜ(2) - ॻ͖΍͗͢͢ΔFutureͷ᠘ - mashi

  2. ScalaͷFuture࠷ߴ •  ͱʹ͔͘ॻ͖΍͍͢ •  flatMap ͱ for ͷߏจ͕ศར͗͢Δ

  3. flatMap/for •  flatMap Ͱ΋ͦͦ͜͜ॻ͖΍͍͢͠ɺforͰ ॻ͘ͱ͞Βʹॻ͖΍͍͢ db.getById(id).flatMap { a => db.getByFuga(a.nanikore).flatMap

    { b => db.updateNanikore(b.piyopiyo).map { c => c.data } } } for { a <- db.getById(id) b <- db.getByFuga(a.nanikore) c <- db.updateNanikore(b.piyopiyo) } yield c.data ↑ಉ͡↑
  4. ໰୊఺ ʊਓਓਓਓਓਓਓਓਓʊ ʼɹॻ͖΍͗͢͢Δɹʻ ʉY^Y^Y^Y^Y^Y^Y^Y^Yʉ ͔͠΋ͦΕͬΆ͘ݟ͑Δ

  5. ΞΧϯྫ – ඞཁͳ͍flatMap(1) •  Ռͨͯ͠notification.notify(a, b) ͷԠ౴Λ ଴͔ͬͯΒϨεϙϯεΛฦ͢ҙຯ͕͋Δͷ ͔ʁ for

    { a <- service.getA(id) b <- service.getB(a.name) _ <- notification.notify(a, b) ֎෦αʔϏε΁ͷ௨஌ } yield b.data
  6. ΞΧϯྫ – ඞཁͳ͍flatMap •  ଴ͭඞཁ͕ͳ͍ɺΤϥʔϋϯυϦϯά͢ Δඞཁ͕ͳ͍ͳΒflatMap͠ͳ͍ for { a <-

    service.getA(id) b <- service.getB(a.name) } yield { notification.notify(a, b) ݁ՌΛ଴ͨͳ͍ b.data } ˞ notification.notify(a, b) ʹࣦഊͨ͠৔߹ʹFuture.failed ʹ͍ͨ͠৔߹ʹ͸ෆద੾ मਖ਼ޙ
  7. •  Ռͨͯ͠serviceA.getA ͷ݁ՌΛ଴͔ͬͯ Βservice.getB Λ࣮ߦ͢Δҙຯ͸͋Δͷ ͔ʁ ΞΧϯྫ – ඞཁͳ͍flatMap(2) val

    id = “randy” for { a <- serviceA.getA(id) b <- serviceB.getB(id) } yield a.name + b.name
  8. •  ͙͢ʹಉ࣌ʹൃՐ͍͍ͯ͠ͳΒͬ͞͞ͱݺ ΜͰ͠·͏ ΞΧϯྫ – ඞཁͳ͍flatMap(2) val id = “randy”

    val aFuture = serviceA.getA(id) val bFuture = serviceB.getB(id) // AͷԠ౴Λ଴͍ͬͯͳ͍ for { a <- aFuture b <- bFuture } yield a.name + b.name ˞'VUVSFͷ[JQ͕ศརʹ࢖͑·͢ɻৄ͘͠͸ௐ΂ͯΈ͍ͯͩ͘͞ मਖ਼ޙ
  9. ΞΧϯྫ – DBτϥϯβΫγϣϯԼ dbTransaction { implicit tx => for {

    a <- db.getById(id) tw <- twitterApi.getA(a.name) b <- db.getByFuga(a.nanikore, tw.a) c <- db.updateNanikore(b.piyopiyo) } yield c.data } DBτϥϯβΫγϣϯதʹ ΋͔ͨ͠͠Β௕͔͔࣌ؒΔ͔΋͠Εͳ͍͜ͱΛ΍ͬͯ͠·͏ τϥϯβΫγϣϯ͕͍ͭ·Ͱͨͬͯ΋ऴΘΒͳ͍͔΋͠Εͳ͍͠ɺ ίωΫγϣϯ΋ղ์͞Εͳ͍
  10. ΞΧϯྫ – DBτϥϯβΫγϣϯԼ मਖ਼ྫ •  ݪଇτϥϯβΫγϣϯԼͰDBͷૢ࡞Ҏ֎ ͷ͜ͱΛ͠ͳ͍ •  Ͳ͏ͯ͠΋ଞͷ͜ͱΛ͢ΔͳΒλΠϜΞ΢ τΛઃ͚Δ

    ˞Ͳ͏ͤJDBC͕ϒϩοΩϯάͳͷͰɺԼखʹFutureΛ࢖Θͣී௨ʹॻ͍ͨ΄͏͕ ͍͍͔΋͠Εͳ͍
  11. ·ͱΊ •  Scala ͷ Future + flatMap + forߏจ͸ศར͗͢Δɻ ͙͢ॻ͚Δ

    •  ͔͠͠Future͑͞࢖͑͹ԿͰ΋ϋΠύϑΥʔϚϯ ε&͍͍ײ͡ʹಈ͘Θ͚Ͱ͸ͳ͍ •  ॻ͍͍ͯΔίʔυ͕͍ͭͲͷΑ͏ʹಈ͘ͷ͔ৗ ʹҙࣝ͢ΔΑ͏ʹ͢Δ –  ౰ͨΓલͷ࿩Ͱ͕͢ɺ׳ΕΔͱଦੑͰॻ͍ͯ͠·͏ͱ ͖͕͋ΔͷͰ…ॳ৺ʹ໭Γ·͠ΐ͏ɻ