_Ziens_

RxJava3 SwingScheduler adapter

Aug 1st, 2020 (edited)
2,140
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import io.reactivex.rxjava3.core.Scheduler
  2. import io.reactivex.rxjava3.disposables.Disposable
  3. import io.reactivex.rxjava3.schedulers.Schedulers
  4. import java.util.concurrent.Executor
  5. import java.util.concurrent.TimeUnit
  6. import javax.swing.SwingUtilities
  7.  
  8. object SwingScheduler : Scheduler() {
  9.  
  10.     private val swingExecutor = Executor { runnable: Runnable ->
  11.         if (SwingUtilities.isEventDispatchThread()) runnable.run() else SwingUtilities.invokeLater(runnable)
  12.     }
  13.  
  14.     private val swingScheduler = Schedulers.from(swingExecutor)
  15.  
  16.     override fun createWorker(): Worker = swingScheduler.createWorker()
  17.  
  18.     override fun schedulePeriodicallyDirect(
  19.         run: Runnable?,
  20.         initialDelay: Long,
  21.         period: Long,
  22.         unit: TimeUnit?
  23.     ): Disposable = swingScheduler.schedulePeriodicallyDirect(run, initialDelay, period, unit)
  24.  
  25.     override fun scheduleDirect(run: Runnable?): Disposable = swingScheduler.scheduleDirect(run)
  26.  
  27.     override fun scheduleDirect(run: Runnable?, delay: Long, unit: TimeUnit?): Disposable =
  28.         swingScheduler.scheduleDirect(run, delay, unit)
  29.  
  30. }
  31.  
  32. // Example of usage:
  33.    viewModel.getLeftScore()
  34.             .observeOn(SwingScheduler)
  35.             .subscribe { score: Int -> leftScoreLabel.text = score.toString() }
RAW Paste Data