Skip to content

Instantly share code, notes, and snippets.

object Coroutines {
fun io(work: suspend (() -> Unit)): Job =
CoroutineScope(Dispatchers.IO).launch {
work()
}
fun <T: Any> ioThenMain(work: suspend (() -> T?), callback: ((T?) -> Unit)): Job =
CoroutineScope(Dispatchers.Main).launch {
val data = CoroutineScope(Dispatchers.IO).async rt@ {
return@rt work()
}.await()
object DataManager {
@WorkerThread
fun dummy(context: Context) {
with(MyDatabase.get(context)) {
users().insert(User(login = "user.name"))
projects().insert(Project(name = "project.name"))
notifications().insert(Notification(msg = "created"))
}
}
@UiThread
fun getUsers(context: Context): LiveData<List<User>> {
if (!::users.isInitialized) {
users = MutableLiveData()
Coroutines.ioThenMain({
DataManager.getUsers(context)
}) {
users.value = it
}
}
inline fun <reified T: Any> Activity.extra(key: String, default: T? = null) = lazy {
val value = intent?.extras?.get(key)
if (value is T) value else default
}
inline fun <reified T: Any> Activity.extraNotNull(key: String, default: T? = null) = lazy {
val value = intent?.extras?.get(key)
requireNotNull(if (value is T) value else default) { key }
}
inline fun <reified T: Any> Fragment.extra(key: String, default: T? = null) = lazy {
val value = arguments?.get(key)
if (value is T) value else default
}
inline fun <reified T: Any> Fragment.extraNotNull(key: String, default: T? = null) = lazy {
val value = arguments?.get(key)
requireNotNull(if (value is T) value else default) { key }
}
const val ID = "id"
class MyActivity : Activity() {
private val id1 by extra<String>(ID) // String?
private val id2 by extraNotNull<String>(ID) // String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireNotNull(id1, id2)
fun requireNotNulls(vararg any: Any?) {
any.forEach {
requireNotNull(value = it)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireNotNulls(id1, id2)
}
class Repository {
init{
}
companion object {
private val CACHE = TimeUnit.HOURS.toSeconds(4)
}
}
fun alwaysReturnsNull(position: Int): String? {
if ((position % 10) == 0) {
when (position) {
10 -> "one"
20, 30 -> "two"
else -> "three"
}
}
return null
}
fun returnsUnit() {
methodReturningBoolean()
}
fun returnsAnImplicitBoolean() = methodReturningBoolean()
private fun methodReturningBoolean() = true