Skip to content

Instantly share code, notes, and snippets.

View Jeff-Soares's full-sized avatar

Jeff Jeff-Soares

  • Rio de Janeiro - RJ
View GitHub Profile
@Jeff-Soares
Jeff-Soares / SimpleHttpRequest.kt
Last active September 15, 2021 21:42
Simple HTTP request using standard library
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL
private fun simpleHttpRequest(): JokeResponse? {
val responseString = StringBuilder()
fun <A : Activity> Activity.startNewActivity(activity: Class<A>) {
Intent(this, activity).also { startActivity(it) }
}
fun Context.toast(msg: String) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
fun Fragment.toast(msg: String) {
requireActivity().toast(msg)
/**
* Extension function to simplify setting an afterTextChanged action to EditText components.
*/
fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
class MainViewModelFactory : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
return modelClass.getConstructor(DependencyClass::class.java)
.newInstance(DependencyClass.newInstance())
} else throw IllegalArgumentException("Unknown ViewModel class")
}
}
sealed class ResultWrapper<out T>(
val data: T? = null,
val error: Throwable? = null
) {
class Success<T>(data: T) : ResultWrapper<T>(data)
class Failure(error: Throwable) : ResultWrapper<Nothing>(error = error)
suspend infix fun <R> then(f: suspend (ResultWrapper<T>) -> ResultWrapper<R>): ResultWrapper<R> {
return when (this) {
is Success -> f(this)