funkwhale-android/app/src/main/java/com/github/apognu/otter/utils/Extensions.kt

82 wiersze
2.1 KiB
Kotlin
Czysty Zwykły widok Historia

2019-08-19 14:50:33 +00:00
package com.github.apognu.otter.utils
2019-10-21 17:49:48 +00:00
import android.content.Context
2019-08-19 14:50:33 +00:00
import android.os.Build
2019-10-21 17:49:48 +00:00
import androidx.core.content.ContextCompat
2019-08-19 14:50:33 +00:00
import androidx.fragment.app.Fragment
2019-10-22 19:56:33 +00:00
import com.github.apognu.otter.R
2019-08-19 14:50:33 +00:00
import com.github.apognu.otter.fragments.BrowseFragment
import com.github.apognu.otter.repositories.Repository
import com.github.kittinunf.fuel.core.Request
2019-10-22 19:56:33 +00:00
import com.squareup.picasso.Picasso
import com.squareup.picasso.RequestCreator
2019-08-19 14:50:33 +00:00
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.GlobalScope
2019-10-31 15:17:37 +00:00
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
2019-08-19 14:50:33 +00:00
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
2019-10-21 17:49:48 +00:00
fun Context.getColor(colorRes: Int): Int {
return ContextCompat.getColor(this, colorRes)
}
2019-10-31 15:17:37 +00:00
inline fun <D> Flow<Repository.Response<D>>.untilNetwork(context: CoroutineContext = Main, crossinline callback: (data: List<D>, isCache: Boolean, hasMore: Boolean) -> Unit) {
2019-08-19 14:50:33 +00:00
GlobalScope.launch(context) {
2019-10-31 15:17:37 +00:00
collect { data ->
callback(data.data, data.origin == Repository.Origin.Cache, data.hasMore)
2019-08-19 14:50:33 +00:00
}
}
}
fun Fragment.onViewPager(block: Fragment.() -> Unit) {
for (f in activity?.supportFragmentManager?.fragments ?: listOf()) {
if (f is BrowseFragment) {
f.block()
}
}
}
fun <T> Int.onApi(block: () -> T) {
if (Build.VERSION.SDK_INT >= this) {
block()
}
}
fun <T, U> Int.onApi(block: () -> T, elseBlock: (() -> U)) {
if (Build.VERSION.SDK_INT >= this) {
block()
} else {
elseBlock()
}
}
fun <T> Int.onApiForResult(block: () -> T, elseBlock: (() -> T)): T {
2019-10-21 09:51:32 +00:00
return if (Build.VERSION.SDK_INT >= this) {
block()
2019-08-19 14:50:33 +00:00
} else {
2019-10-21 09:51:32 +00:00
elseBlock()
2019-08-19 14:50:33 +00:00
}
}
fun <T> T.applyOnApi(api: Int, block: T.() -> T): T {
2019-10-21 09:51:32 +00:00
return if (Build.VERSION.SDK_INT >= api) {
block()
2019-08-19 14:50:33 +00:00
} else {
2019-10-21 09:51:32 +00:00
this
2019-08-19 14:50:33 +00:00
}
2019-10-22 19:56:33 +00:00
}
fun Picasso.maybeLoad(url: String?): RequestCreator {
if (url == null) return load(R.drawable.cover)
else return load(url)
}
fun Request.authorize(): Request {
return this.apply {
if (!Settings.isAnonymous()) {
header("Authorization", "Bearer ${Settings.getAccessToken()}")
}
}
}