Skip to content

Instantly share code, notes, and snippets.

View iambaljeet's full-sized avatar

Baljeet Singh iambaljeet

View GitHub Profile
<?xml version="1.0" encoding="utf-8"?>
<navigation 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"
android:id="@+id/main_nav_graph"
app:startDestination="@id/oneFragment">
<fragment android:id="@+id/oneFragment"
android:name="com.app.kotlinnavigation.OneFragment"
android:label="fragment_one"
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
implementation 'com.squareup.okhttp3:logging-interceptor:4.1.1'
// Kotlin Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
interface ApiService {
companion object {
val BASE_URL: String = "https://demo.dataverse.org/api/"
}
@GET("search")
suspend fun getResult(
@Query("q") query: String?): Response<SearchResultModel?>
}
data class SearchResultModel(
val `data`: Data?,
val status: String?
) {
data class Data(
val count_in_response: Int?,
val items: List<Item?>?,
val q: String?,
val spelling_alternatives: SpellingAlternatives?,
val start: Int?,
object ApiProvider {
private val retrofit = Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.client(getHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build()
private fun getHttpClient(): OkHttpClient {
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
object DataRepository {
var apiService: ApiService? = null
var searchResultsLiveData: MutableLiveData<GenericDataModel<SearchResultModel>?> = MutableLiveData()
init {
apiService =
ApiProvider.createService(
ApiService::class.java
)
}
data class GenericDataModel<T>(val isSuccess: Boolean?, val data: T?, val message: String?)
private fun startSearching(searchQuery: String?) {
apiJob = CoroutineScope(Dispatchers.IO).launch {
DataRepository.getSearchResults(searchQuery)
withContext(Dispatchers.Main) {
DataRepository.searchResultsLiveData.observe(
this@MainActivity,
Observer { genericDataModel: GenericDataModel<SearchResultModel>? ->
run {
if (genericDataModel?.isSuccess == true) {
searchEditText?.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {
resultTextView?.visibility = View.GONE
progressLoading?.visibility = View.VISIBLE
apiJob?.cancel()
startSearching(s.toString())
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
private fun startSearching(searchQuery: String?) {
CoroutineScope(Dispatchers.IO).launch {
DataRepository.getSearchResults(searchQuery)
withContext(Dispatchers.Main) {
}
}
}