Skip to content

Instantly share code, notes, and snippets.

View TheBotBox's full-sized avatar
🖥️
coding

TheBotBox TheBotBox

🖥️
coding
View GitHub Profile
<layout>
<data>
<variable
name="viewModel"
type="com.thebotbox.letsmvvm.presentation.viewmodel.MainViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
class MainActivity : AppCompatActivity() {
private val mBinding by viewBinding(ActivityMainBinding::inflate)
private val mViewModel by viewModel<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(mBinding.root)
mBinding.viewModel = mViewModel
mViewModel.fetchRandomQuoteLiveData.observe(this, Observer { // observing response from viewmodel
class MainViewModel(
private val iRepository: IRepository
) : ViewModel() {
private val _errorLiveData: MutableLiveData<String> = MutableLiveData()
val errorLiveData: LiveData<String>
get() = _errorLiveData
private val _fetchRandomQuoteLiveData: MutableLiveData<RandomQuoteResponse> = MutableLiveData()
val fetchRandomQuoteLiveData: LiveData<RandomQuoteResponse>
inline fun <reified T> Any.ofType(block: (T) -> Unit) {
if (this is T) {
block(this as T)
}
}
fun Activity.requestPermissions(vararg permissions: String, @IntRange(from = 0) requestCode: Int) =
ActivityCompat.requestPermissions(this, permissions, requestCode)
fun AppCompatActivity.hasPermissions(vararg permissions: String): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
permissions.all { singlePermission ->
applicationContext.checkSelfPermission(singlePermission) == PackageManager.PERMISSION_GRANTED
}
else true
val <T> T.makeExhaustive: T
get() = this
fun EditText.onDone(callback: (String) -> Unit) {
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
callback.invoke(text.toString())
true
}
false
}
}
fun EditText.onTextChanged(listener: (String) -> Unit) {
this.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) { listener(s.toString()) }
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
}
inline fun <reified E : Throwable> tryAndCatch(blockTry: () -> Unit, blockCatch: (E) -> Unit) {
try {
blockTry()
} catch (e: Exception) {
blockCatch(e as E)
}
}