|
| 1 | +# Publishers |
| 2 | + |
| 3 | +The FateWeaver extension includes an additional feature called publishers, |
| 4 | +which allow you to register a channel that will be automatically logged to |
| 5 | +every loop. |
| 6 | + |
| 7 | +Take our [lift subsystem](../../guide/subsystems/lift) from the guide. |
| 8 | +Let's add a public `state` getter: |
| 9 | + |
| 10 | +:::tabs key:code |
| 11 | + |
| 12 | +== Kotlin |
| 13 | + |
| 14 | +```kotlin |
| 15 | +val state get() = motor.state |
| 16 | +``` |
| 17 | + |
| 18 | +== Java |
| 19 | + |
| 20 | +```java |
| 21 | +public KineticState getState() { |
| 22 | + return motor.getState(); |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +::: |
| 27 | + |
| 28 | +Now, in the `onStartButtonPressed` method of our OpMode, |
| 29 | +we can register a publisher for the lift's state: |
| 30 | + |
| 31 | +:::tabs key:code |
| 32 | + |
| 33 | +== Kotlin |
| 34 | + |
| 35 | +```kotlin |
| 36 | +val stateChannel = FateComponent.createChannel("Lift State", KineticState::class) |
| 37 | +FateComponent.registerPublisher(stateChannel, Lift::state) |
| 38 | +``` |
| 39 | + |
| 40 | +== Java |
| 41 | + |
| 42 | +```java |
| 43 | +LogChannel<KineticState> stateChannel = FateComponent.createChannel("LiftState", KineticState.class); |
| 44 | +FateComponent.registerPublisher(stateChannel, Lift.INSTANCE::getState); |
| 45 | +``` |
| 46 | + |
| 47 | +::: |
| 48 | + |
| 49 | +This will automatically publish the lift's state to the log file at the end of every loop. |
| 50 | + |
| 51 | +There is an overload for `registerPublisher` that takes a |
| 52 | +channel name and schema (or class) instead of a channel object, |
| 53 | +which could be used as follows: |
| 54 | + |
| 55 | +:::tabs key:code |
| 56 | + |
| 57 | +== Kotlin |
| 58 | + |
| 59 | +```kotlin |
| 60 | +FateComponent.registerPublisher("LiftState", KineticState::class, Lift::state) |
| 61 | +``` |
| 62 | + |
| 63 | +== Java |
| 64 | + |
| 65 | +```java |
| 66 | +FateComponent.registerPublisher("LiftState", KineticState.class, Lift.INSTANCE::getState); |
| 67 | +``` |
| 68 | + |
| 69 | +::: |
| 70 | + |
| 71 | +Publishers are automatically unregistered when the OpMode ends. |
| 72 | + |
| 73 | +In this example, we use method and property references to simplify the code, |
| 74 | +but you can also use lambda expressions. |
| 75 | +WPILib has has an amazing explanation of method references and lambda expressions |
| 76 | +[here](https://docs.wpilib.org/en/stable/docs/software/basic-programming/functions-as-data.html). |
| 77 | +For information on Kotlin method references and lambda expressions, |
| 78 | +see [the Kotlin documentation](https://kotlinlang.org/docs/lambdas.html). |
0 commit comments