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

KotlinJSでもCoroutines

 KotlinJSでもCoroutines

2018.07.03 Kotlin愛好会 vol2
create-react-kotlin-appでサンプルプロジェクトを作り、その上でcoroutinesを動かしてみます。

Ryo Sakaguchi

July 03, 2018
Tweet

More Decks by Ryo Sakaguchi

Other Decks in Programming

Transcript

  1. About me • Ryo Sakaguchi (@wakwak3125) • Wantedly People •

    AndroidͷਓͰ͢ • Snowboard/Guitar/Beer
  2. These posts are useful! • Coroutines - Kotlin Programming Language

    • https://kotlinlang.org/docs/reference/coroutines.html • ׬શʹཧղͨ͠ؾʹͳΔKotlin Coroutines by @takahirom • https://qiita.com/takahirom/items/ 2ba221a8d0c32cf701ba • ೖ໳Kotlin coroutines @k-kagurazaka • https://qiita.com/k-kagurazaka@github/items/
  3. ͔͍͔ͭͨ • $ npm install -g create-react-kotlin-app • $ create-react-kotlin-app

    my-app • done!! • $ yarn start͢ΔͱlocalhostͰಈ࡞֬ೝͰ͖Δ
  4. App.kt class App : RComponent<RProps, RState>() { override fun RBuilder.render()

    { div("App-header") { logo() h2 { +"Welcome to React with Kotlin" } } p("App-intro") { +"To get started, edit " code { +"app/App.kt" } +" and save to reload." } p("App-ticker") { ticker() } } } fun RBuilder.app() = child(App::class) {}
  5. Ticker.kt class Ticker(props: TickerProps) : RComponent<TickerProps, TickerState>(props) { override fun

    TickerState.init(props: TickerProps) { secondsElapsed = props.startFrom } var timerID: Int? = null override fun componentDidMount() { timerID = window.setInterval({ setState { secondsElapsed += 1 } }, 1000) } override fun componentWillUnmount() { window.clearInterval(timerID!!) } override fun RBuilder.render() { +"This app has been running for ${state.secondsElapsed} seconds." } } fun RBuilder.ticker(startFrom: Int = 0) = child(Ticker::class) { attrs.startFrom = startFrom }
  6. TickerͷStateͱProps interface TickerProps : RProps { var startFrom: Int }

    interface TickerState : RState { var secondsElapsed: Int }
  7. Tickerͷ࣮૷ setIntervalͰ1ඵ͝ͱʹΧ΢ϯτΞοϓ var timerId: Int? = null override fun componentDidMount()

    { timerID = window.setInterval({ setState { secondsElapsed += 1 } }, 1000) }
  8. Tickerͷ࣮૷ setIntervalͰ1ඵ͝ͱʹΧ΢ϯτΞοϓ var timerId: Int? = null override fun componentDidMount()

    { timerID = window.setInterval({ setState { secondsElapsed += 1 } }, 1000) } => CoroutineԽͯ͠ΈΑ͏
  9. CoroutineԽͯ͠ΈΔ var job: Job? = null override fun componentDidMount() {

    job = launch { while (true) { delay(1000) setState { secondsElapsed += 1 } } } } => done!
  10. fetch • fetch΋΋ͪΖΜ࢖͑Δ // ίʔυ͸งғؾ suspend fun getFoo(): Any =

    suspendCoroutine { cont -> window .fetch("https://foo.com/api/foo") .then({ response -> cont.resume(response.ok.toString()) },{ throwable -> cont.resumeWithException(throwable) }) } // ී௨ʹ࢖͏ launce { val foo = getFoo() }