How can i implement counterpart of SurfaceView used with another thread to draw and update in a specific interval in Jetpack Compose?
And with coroutines i use it like this
abstract class CoroutineSurfaceView : SurfaceView, SurfaceHolder.Callback,
DefaultLifecycleObserver {
// Handle works in thread that exception is caught that are
private val handler = CoroutineExceptionHandler { coroutineContext, throwable ->
}
internal lateinit var canvas: Canvas
var framePerSecond = 60
private var renderTime = 100L / framePerSecond
private val coroutineScope = CoroutineScope(handler + SupervisorJob() + Dispatchers.Default)
private lateinit var job: Job
private lateinit var surfaceHolder: SurfaceHolder
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context)
}
constructor(context: Context) : super(context) {
init(context)
}
open fun init(context: Context) {
surfaceHolder = this.holder
surfaceHolder.addCallback(this)
setZOrderOnTop(true)
}
override fun surfaceCreated(holder: SurfaceHolder) {
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
}
private fun startCoroutineRendering() {
job = coroutineScope.launch {
while (isActive) {
if (!surfaceHolder.surface.isValid) {
continue
}
canvas = surfaceHolder.lockCanvas()
update()
render(canvas)
holder.unlockCanvasAndPost(canvas)
delay(renderTime)
}
}
}
internal abstract fun update()
internal abstract fun render(canvas: Canvas)
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
startCoroutineRendering()
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
coroutineScope.launch(Dispatchers.Main.immediate) {
job.cancelAndJoin()
}
}
}