Skip to content

Instantly share code, notes, and snippets.

@yaraki
Created September 28, 2018 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaraki/404cb95db96737c55fc6e3454cf81ff7 to your computer and use it in GitHub Desktop.
Save yaraki/404cb95db96737c55fc6e3454cf81ff7 to your computer and use it in GitHub Desktop.
FPS as LiveData (with coroutine)
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.yaraki.playground
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.android.Main
import kotlinx.coroutines.experimental.android.awaitFrame
import kotlinx.coroutines.experimental.isActive
import kotlinx.coroutines.experimental.launch
import java.util.concurrent.TimeUnit
class MainViewModel : ViewModel() {
private val job = Job()
private val scope = CoroutineScope(Dispatchers.Main + job)
val fps: LiveData<String> by lazy(LazyThreadSafetyMode.NONE) {
MutableLiveData<String>().also { liveData ->
scope.launch {
var count = 0
val oneSecond = TimeUnit.SECONDS.toNanos(1)
var start = System.nanoTime()
while (isActive) {
val now = awaitFrame()
count++
if (now - start >= oneSecond) {
liveData.value = count.toString()
count = 0
start = now
}
}
}
}
}
override fun onCleared() {
super.onCleared()
job.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment