Search code examples
androidtwitterretrofit2twitter-streaming-api

How to call filtered twitter STREAM API in android?


I want to stream twitter tweets continuously with twitter stream api with retrofit and without any 3rd party libraries. When i try to call the api " https://api.twitter.com/2/tweets/search/stream " I'm only getting the result first time. How to stream it?


Solution

  • I have finally achieved it using this snippet

    override suspend fun streamTweets(): Flow<Resource<TweetResponseModel>> {
            return flow {
                val client: OkHttpClient = OkHttpClient().newBuilder().addInterceptor(
                    BasicAuthInterceptor(getAPIKey(), getAPISecretKey())
                ).build()
    
            val request: Request = Request.Builder()
                .url(TWITTER_STREAM_URL)
                .method("GET", null)
                .build()
            val response: okhttp3.Response = client.newCall(request).execute()
            val source = response.body?.source()
            val buffer = Buffer()
            while (!source!!.exhausted()) {
                response.body?.source()?.read(buffer, 8192)
                val data = buffer.readString(Charset.defaultCharset())
                try {
                    val tweetResponseModel: TweetResponseModel =
                        Gson().fromJson(data, TweetResponseModel::class.java)
                    emit(Resource.Success(tweetResponseModel))
                } catch (e: Exception) {
                    Log.e("jsonException", data)
                }
            }
        }.flowOn(ioDispatcher)
    
    }