Skip to content

Instantly share code, notes, and snippets.

@mattiaferigutti
Last active March 4, 2021 18:27
Show Gist options
  • Save mattiaferigutti/532f23ac7510c02bf29888d21d57ce15 to your computer and use it in GitHub Desktop.
Save mattiaferigutti/532f23ac7510c02bf29888d21d57ce15 to your computer and use it in GitHub Desktop.
package com.studio.mattiaferigutti.hilt_usage_sample
interface ApiService {
suspend fun getText() : Reply
}
package com.studio.mattiaferigutti.hilt_usage_sample
import okhttp3.*
import java.io.IOException
import javax.inject.Inject
class ApiServiceImpl @Inject constructor(private val request: Request) : ApiService {
override suspend fun getText(): Reply {
var result = ""
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
result = e.toString()
}
override fun onResponse(call: Call, response: Response) {
result = response.body.toString()
}
})
return Reply(result)
}
}
package com.studio.mattiaferigutti.hilt_usage_sample
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityComponent
import dagger.hilt.android.internal.managers.ApplicationComponentManager
import dagger.hilt.components.SingletonComponent
import okhttp3.*
import java.io.IOException
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class ApplicationModule {
@Provides
@Singleton
fun provideRetrofit() : Request {
return Request.Builder()
.url("http://www.massimocarli.eu/bus/bus_stop.json")
.build()
}
@Provides
fun provideApiService(request: Request) : ApiService {
return ApiServiceImpl(request)
}
}
package com.studio.mattiaferigutti.hilt_usage_sample
import javax.inject.Inject
class MainRepository @Inject constructor(val result: ApiService) {
suspend fun getResult() : String {
return result.getText().message
}
}
package com.studio.mattiaferigutti.hilt_usage_sample
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class SecondFragmentViewModel @ViewModelInject constructor(
private val mainRepository: MainRepository
)
: ViewModel() {
private val _data = MutableLiveData<String>()
val data : LiveData<String>
get() = _data
init {
fetch()
}
private fun fetch() {
viewModelScope.launch {
_data.postValue(mainRepository.getResult())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment