Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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

mashijp
November 13, 2015

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

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

mashijp

November 13, 2015
Tweet

More Decks by mashijp

Other Decks in Programming

Transcript

  1. 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 ↑ಉ͡↑
  2. ΞΧϯྫ – ඞཁͳ͍flatMap(1) •  Ռͨͯ͠notification.notify(a, b) ͷԠ౴Λ ଴͔ͬͯΒϨεϙϯεΛฦ͢ҙຯ͕͋Δͷ ͔ʁ for

    { a <- service.getA(id) b <- service.getB(a.name) _ <- notification.notify(a, b) ֎෦αʔϏε΁ͷ௨஌ } yield b.data
  3. ΞΧϯྫ – ඞཁͳ͍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 ʹ͍ͨ͠৔߹ʹ͸ෆద੾ मਖ਼ޙ
  4. •  Ռͨͯ͠serviceA.getA ͷ݁ՌΛ଴͔ͬͯ Βservice.getB Λ࣮ߦ͢Δҙຯ͸͋Δͷ ͔ʁ ΞΧϯྫ – ඞཁͳ͍flatMap(2) val

    id = “randy” for { a <- serviceA.getA(id) b <- serviceB.getB(id) } yield a.name + b.name
  5. •  ͙͢ʹಉ࣌ʹൃՐ͍͍ͯ͠ͳΒͬ͞͞ͱݺ ΜͰ͠·͏ ΞΧϯྫ – ඞཁͳ͍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͕ศརʹ࢖͑·͢ɻৄ͘͠͸ௐ΂ͯΈ͍ͯͩ͘͞ मਖ਼ޙ
  6. ΞΧϯྫ – 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τϥϯβΫγϣϯதʹ ΋͔ͨ͠͠Β௕͔͔࣌ؒΔ͔΋͠Εͳ͍͜ͱΛ΍ͬͯ͠·͏ τϥϯβΫγϣϯ͕͍ͭ·Ͱͨͬͯ΋ऴΘΒͳ͍͔΋͠Εͳ͍͠ɺ ίωΫγϣϯ΋ղ์͞Εͳ͍
  7. ·ͱΊ •  Scala ͷ Future + flatMap + forߏจ͸ศར͗͢Δɻ ͙͢ॻ͚Δ

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