Created
March 18, 2022 14:36
-
-
Save rjrjr/42a13f9395a2b30df4704d38ebfa9d99 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.squareup.sample.compose.hellocomposebinding | |
import com.squareup.sample.compose.hellocomposebinding.HelloWorkflow.Rendering | |
import com.squareup.sample.compose.hellocomposebinding.HelloWorkflow.HG | |
import com.squareup.sample.compose.hellocomposebinding.HelloWorkflow.HG.Goodbye | |
import com.squareup.sample.compose.hellocomposebinding.HelloWorkflow.HG.Hello | |
import com.squareup.sample.compose.hellocomposebinding.HelloWorkflow.State | |
import com.squareup.sample.compose.hellocomposeworkflow.HelloWorkflow | |
import com.squareup.workflow1.Snapshot | |
import com.squareup.workflow1.StatefulWorkflow | |
import com.squareup.workflow1.action | |
import com.squareup.workflow1.asWorker | |
import com.squareup.workflow1.parse | |
import com.squareup.workflow1.runningWorker | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.flow.flow | |
object HelloWorkflow : StatefulWorkflow<Unit, State, Nothing, Rendering>() { | |
data class State( | |
val hg: HG = Hello, | |
val plus: String = "" | |
) | |
enum class HG { | |
Hello, | |
Goodbye; | |
fun toggle(): HG = when (this) { | |
Hello -> Goodbye | |
Goodbye -> Hello | |
} | |
} | |
data class Rendering( | |
val message: String, | |
val onClick: () -> Unit | |
) | |
private val helloAction = action { | |
state = state.copy(hg = state.hg.toggle()) | |
} | |
private val pulseAction = action { | |
state = state.copy(plus = if (state.plus.isBlank()) "*" else "") | |
} | |
private val pulseWorker = flow { | |
while (true) { | |
delay(1000L) | |
emit(Unit) | |
} | |
}.asWorker() | |
override fun initialState( | |
props: Unit, | |
snapshot: Snapshot? | |
): State = | |
snapshot?.bytes?.parse { source -> if (source.readInt() == 1) State() else State(Goodbye) } | |
?: State() | |
override fun render( | |
renderProps: Unit, | |
renderState: State, | |
context: RenderContext | |
): Rendering { | |
context.runningWorker(pulseWorker) { pulseAction } | |
return Rendering( | |
message = renderState.hg.name + renderState.plus, | |
onClick = { context.actionSink.send(helloAction) } | |
) | |
} | |
override fun snapshotState(state: State): Snapshot = Snapshot.of(if (state.hg == Hello) 1 else 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A tweak to the Hello Compose Binding sample that shows off running a simple worker. See line 66.