Skip to content

Instantly share code, notes, and snippets.

View satoshun's full-sized avatar
🤖

Sato Shun satoshun

🤖
View GitHub Profile
@Test fun list() {
  println(measureTimeMillis {
    println((0..10000000)
        .filter { it % 2 == 0}
        .map { it * it }
        .map { it - 10 }.size)
  })
}
class MutableErrorLiveData<T> : MutableLiveData<Notification<T>>() {
fun observe(owner: LifecycleOwner, onNext: (T) -> Unit, onError: (Throwable) -> Unit) {
observe(owner, Observer { notification ->
notification ?: return@Observer
if (notification.isOnNext) {
onNext(notification.value!!)
} else if (notification.isOnError) {
onError(notification.error!!)
}
})
@satoshun
satoshun / kotlin_cache.kt
Last active November 27, 2017 00:41
Kotlin and RxJava Cacheのコード part1
class UserRepository(
userDao: UserDao
) {
private val userDaoWithCache = Cache(userDao::getUser)
fun getUser(id: Int, name: String): Single<User> {
return userDaoWithCache.fetchOrCache(id, name)
}
}
class UserRepository2(
userDao: UserDao
) {
private val userDaoWithCache = Cache2(userDao::getUser)
private val userDao2WithCache = Cache2(userDao::getUser2)
fun getUser(id: Int, name: String): Single<User> =
userDaoWithCache(id, name)
fun getUser2(id: Int, name: String, password: String): Single<User> =
class UserRepository4(
original: UserDao
) {
private val withCache = cache(original::getUser)
private val withCache2 = cache(original::getUser2)
fun getUser(id: Int, name: String): Single<User> = withCache(id, name)
}
interface UserDao {
class HogeActivity : Activity() {
 …
 …
private fun isHeavyUser(loginCount: Int, firstAccess: Boolean) : Boolean() {
 return firstAccess || (loginCount >= 10 && loginCount <= 100)
 }
}
class HogeActivity : Activity() {
 private fun isHeavyUser(loginCount: Int, firstAccess: Boolean) : Boolean() {
 // hyper HeavyUser if loginCount > 100. hyper HeavyUser doesn’t contain a HeavyUser.
 return firstAccess || (loginCount >= 10 && loginCount <= 100)
 }
}
data class User(private val loginCount: Int, private val firstAccess: Boolean) {
  private fun isHeavyUser() : Boolean() {
 // hyper HeavyUser if loginCount > 100. hyper HeavyUser doesn’t contain a HeavyUser.
  return firstAccess || (loginCount >= 10 && loginCount <= 100)
 }
private fun hyperHeavyUser(): Boolean() { /** */ }
}
interface RRR {
@GET("data/2.5/weather")
fun _getWeather(
@Query("a1") a1: Int,
@Query("a2") a2: String
): Deferred<Resp>
}
val RRR.getWeather get() = ::_getWeather.toSuspend
@UseExperimental(ExperimentalContracts::class)
fun <T : Activity> ActivityScenario<T>.onActivity2(block: (T) -> Unit) {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
onActivity {
block(it)
}
}