Skip to content

Instantly share code, notes, and snippets.

@Alireza-Farahani
Alireza-Farahani / Coroutine Alert Dialog.kt
Last active December 30, 2020 09:25
Using Kotlin coroutines, you can work with AlerDialog and get result from it as if you're writing synchronous code
viewLifecycleOwner.lifecycleScope.launch {
val items = arrayOf("Foo", "Bar", "Baz")
val currentCheckedIdx = 0
val newCheckedItem = suspendCancellableCoroutine<String> { cont ->
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.some_title)
.setSingleChoiceItems(
modesStrings,
currentCheckedIdx
) { dialog, which: Int ->
@Alireza-Farahani
Alireza-Farahani / FragmentExtensions.kt
Created December 31, 2020 13:45
Overriding back button in fragments was never this easy!
fun Fragment.overrideBackButtonWith(block: () -> Unit) {
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
block()
remove() // remove this back button handler
}
})
}
@Alireza-Farahani
Alireza-Farahani / processors.py
Last active June 26, 2022 09:27
Extra Scrapy item processors
# All of these process could be easily written with lambda functions.
# However in combining with Scrapy Compose and MapCompose, I think Processor objects are more consice and readable.
class DropLast:
def __call__(self, values: Sequence):
return values[:-1]
class TakeWhile:
def __init__(self, condition: Callable[[Any], bool]):
self.condition = condition
@Alireza-Farahani
Alireza-Farahani / PostsDatabaseHelper.java
Created September 5, 2023 07:26
Codes for SQLDelight Blog
public class PostsDatabaseHelper extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_POSTS_TABLE = "CREATE TABLE " + TABLE_POSTS +
"(" +
KEY_POST_ID + " INTEGER PRIMARY KEY," + // Define a primary key
KEY_POST_USER_ID_FK + " INTEGER REFERENCES " + TABLE_USERS + "," + // Define a foreign key
KEY_POST_TEXT + " TEXT" +
")";